Introduction to Dynamic Memory Allocation
Static vs. Dynamic Memory Allocation:
o Static Memory Allocation: Memory is allocated at compile time, and the size of
the variables or arrays must be known beforehand. E.g., arrays with fixed size.
o Dynamic Memory Allocation: Memory is allocated at runtime, and the size of
the memory can change as needed during program execution.
Key Advantages:
o Flexibility to allocate memory based on program needs.
o Efficient memory usage since memory can be allocated and freed as required.
o Useful for implementing data structures like linked lists, trees, and graphs.
Library Functions for Dynamic Memory Allocation
a) malloc (Memory Allocation)
Syntax:
void* malloc(size_t size);
Description:
o Allocates a block of memory of size bytes.
o Returns a pointer to the first byte of the allocated memory.
o The allocated memory is uninitialized.
o If the allocation fails (e.g., insufficient memory), it returns NULL.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*)malloc(5 * sizeof(int)); // Allocating memory for 5 integers
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < 5; i++) {
ptr[i] = i + 1; // Initializing memory
}
for (int i = 0; i < 5; i++) {
printf("%d ", ptr[i]);
}
free(ptr); // Freeing allocated memory
return 0;
}
Key Points:
o Always cast the returned pointer to the appropriate data type (e.g., (int*)).
o Memory allocated with malloc is not initialized; it contains garbage values.
b) calloc (Contiguous Allocation)
Syntax:
void* calloc(size_t num, size_t size);
Description:
o Allocates memory for an array of num elements, each of size size.
o The allocated memory is initialized to zero.
o Returns a pointer to the allocated memory block, or NULL if the allocation fails.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*)calloc(5, sizeof(int)); // Allocating memory for 5 integers
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", ptr[i]); // Memory is initialized to 0
}
free(ptr); // Freeing allocated memory
return 0;
}
Key Points:
o Preferred over malloc when zero-initialized memory is needed.
o Useful for creating arrays where all elements must initially be zero.
c) realloc (Reallocate Memory)
Syntax:
void* realloc(void* ptr, size_t new_size);
Description:
o Changes the size of a previously allocated memory block.
o The pointer ptr must point to memory previously allocated by malloc, calloc, or
realloc.
o The content of the original memory block is preserved up to the lesser of the new
and old sizes.
o If the new size is larger, the additional memory is uninitialized.
o Returns a pointer to the reallocated memory, or NULL if the reallocation fails.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*)malloc(3 * sizeof(int)); // Allocating memory for 3 integers
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < 3; i++) {
ptr[i] = i + 1;
}
// Reallocate memory to hold 5 integers
ptr = (int*)realloc(ptr, 5 * sizeof(int));
if (ptr == NULL) {
printf("Memory reallocation failed\n");
return 1;
}
// Initialize additional memory
for (int i = 3; i < 5; i++) {
ptr[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", ptr[i]);
}
free(ptr); // Freeing memory
return 0;
}
Key Points:
o If ptr is NULL, realloc behaves like malloc.
o If new_size is 0, realloc frees the memory and returns NULL
d) free (Deallocate Memory)
Syntax:
void free(void* ptr);
Description:
o Frees the memory previously allocated by malloc, calloc, or realloc.
o The pointer ptr must not be used after calling free (it becomes a dangling pointer).
o Freeing memory helps avoid memory leaks.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*)malloc(5 * sizeof(int)); // Allocate memory
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
free(ptr); // Free memory
return 0;
}
Key Points:
o Always free dynamically allocated memory to avoid memory leaks.
o After freeing, set the pointer to NULL to avoid using a dangling pointer.
Comparison of malloc, calloc, realloc, and free
Function Purpose Initialization Memory Allocation
No (contains
malloc Allocates a block of memory Single block of specified size
garbage)
Allocates memory for an Yes (initialized to Multiple blocks (array) of
calloc
array 0) memory
Resizes previously allocated Preserves existing Changes size of previously
realloc
memory data allocated block
free Frees allocated memory N/A Deallocates memory
Common Errors in Dynamic Memory Allocation
1. Memory Leaks: Forgetting to free allocated memory.
2. Dangling Pointers: Using a pointer after freeing it.
3. Null Pointer Dereference: Not checking if the allocation was successful before using the
pointer
File Handling in C
File handling in C allows programmers to store data in files, retrieve it, and manipulate it
efficiently. This feature is crucial for creating robust programs that require data persistence.
1. Basics of File Handling
Definition: File handling refers to the process of creating, reading, writing, and
managing files using C programs.
Importance of File Handling:
o Data storage and retrieval.
o Allows programs to maintain records even after the program terminates.
o Supports structured data organization.
2. File Types
C programs can work with two types of files:
1. Text Files:
o Contain human-readable characters.
o End each line with a newline character (\n).
o Example: .txt files.
o Functions: fprintf(), fscanf(), fgets(), etc.
2. Binary Files:
o Contain data in binary form (0s and 1s).
o Not human-readable.
o Efficient for storing complex data like structures.
o Functions: fwrite(), fread(), etc.
3. File Operations
The key operations in file handling are:
1. Creating a file: Using functions like fopen().
2. Opening a file: Accessing the file for reading, writing, or both.
3. Reading from a file: Using functions like fscanf(), fgets(), or fread().
4. Writing to a file: Using functions like fprintf(), fputs(), or fwrite().
5. Closing a file: Ensures all data is saved and frees up system resources. Use fclose().
4. File Pointer
Definition: A file pointer is a pointer of type FILE that stores information about a file
opened using fopen().
Declaration:
FILE *fp;
Usage:
o Points to the beginning of the file when opened.
o Tracks the current position during read/write operations.
5. File Opening Modes
The mode determines how the file will be accessed. Common modes are:
Mode Description
r Opens a file for reading. Returns NULL if the file does not exist.
w Opens a file for writing. Creates the file if it doesn’t exist.
a Opens a file for appending. Creates the file if it doesn’t exist.
r+ Opens a file for both reading and writing.
w+ Opens a file for both reading and writing. Overwrites existing content.
a+ Opens a file for both reading and appending.
rb, wb, ab Same as above, but for binary files.
6. File Handling Functions
Here are some commonly used functions in file handling:
1. fopen(): Opens a file.
FILE *fopen(const char *filename, const char *mode);
Example:
FILE *fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("Error opening file\n");
}
2. fclose(): Closes an opened file.
int fclose(FILE *fp);
Example:
fclose(fp);
3. fprintf() and fscanf(): Read/write formatted data.
fprintf(fp, "Name: %s, Age: %d\n", name, age);
fscanf(fp, "%s %d", name, &age);
4. fgets() and fputs(): Work with strings.
char str[100];
fgets(str, 100, fp); // Reads a line
fputs(str, fp); // Writes a line
5. fread() and fwrite(): Work with binary data.
size_t fread(void *ptr, size_t size, size_t count, FILE *fp);
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
6. fseek() and ftell(): Random file access.
o fseek(FILE *fp, long offset, int origin);
o ftell(FILE *fp);
Example:
fseek(fp, 0, SEEK_END); // Move to end of file
long size = ftell(fp); // Get current file position
7. File Handling Through Command-Line Arguments
Concept: Command-line arguments allow files to be specified when running the
program.
Example:
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
// Perform file operations
fclose(fp);
return 0;
}
8. Record I/O in Files
Concept: Storing and retrieving structured data (e.g., arrays or structures) in files.
Example: Writing and reading student records
#include <stdio.h>
struct Student {
char name[50];
int roll;
float marks;
};
int main() {
FILE *fp;
// Writing records to a text file
fp = fopen("[Link]", "w"); // Open the file in write mode
struct Student s1 = {"John", 101, 95.5};
fprintf(fp, "%s %d %.2f\n", [Link], [Link], [Link]); // Write the record
fclose(fp);
// Reading records from the text file
fp = fopen("[Link]", "r"); // Open the file in read mode
struct Student s2;
fscanf(fp, "%s %d %f", [Link], &[Link], &[Link]); // Read the record
printf("Name: %s, Roll: %d, Marks: %.2f\n", [Link], [Link], [Link]); // Print the record
fclose(fp);
return 0;
Example: Reading, Writing, and Appending to a Text File
This program will:
1. Write data to a text file.
2. Read data from the file.
3. Append additional data to the file.
c
Copy code
#include <stdio.h>
int main() {
FILE *file;
char data[100];
// WRITE Operation
// Opening the file in write mode ("w") - This will create a new file or overwrite an existing
one.
file = fopen("[Link]", "w");
if (file == NULL) {
printf("Unable to open the file for writing.\n");
return 1; // Exit the program if the file cannot be opened
}
fprintf(file, "This is a test line written to the file.\n");
fprintf(file, "Writing more data into the file.\n");
fclose(file); // Close the file after writing
// READ Operation
// Opening the file in read mode ("r")
file = fopen("[Link]", "r");
if (file == NULL) {
printf("Unable to open the file for reading.\n");
return 1; // Exit the program if the file cannot be opened
}
printf("Reading the file contents:\n");
while (fgets(data, sizeof(data), file) != NULL) {
printf("%s", data); // Print each line read from the file
}
fclose(file); // Close the file after reading
// APPEND Operation
// Opening the file in append mode ("a") - This will add data at the end of the file.
file = fopen("[Link]", "a");
if (file == NULL) {
printf("Unable to open the file for appending.\n");
return 1; // Exit the program if the file cannot be opened
}
fprintf(file, "This line is appended to the file.\n");
fclose(file); // Close the file after appending
// Check if the data is correctly appended by reading the file again
file = fopen("[Link]", "r");
if (file == NULL) {
printf("Unable to open the file for reading.\n");
return 1; // Exit the program if the file cannot be opened
}
printf("\nReading the file after appending:\n");
while (fgets(data, sizeof(data), file) != NULL) {
printf("%s", data); // Print each line read from the file
}
fclose(file); // Close the file after reading
return 0;
}
Explanation of the Code:
1. Write Operation (fopen("[Link]", "w")):
o The file is opened in write mode ("w"). If the file does not exist, it is created. If
the file already exists, it is overwritten.
o fprintf() is used to write data into the file.
2. Read Operation (fopen("[Link]", "r")):
o The file is opened in read mode ("r"), and fgets() is used to read each line from
the file. The content of the file is printed on the console.
o The fgets() function reads each line until it encounters a newline character or the
end of the file.
3. Append Operation (fopen("[Link]", "a")):
o The file is opened in append mode ("a"), which adds data at the end of the file
without modifying existing data.
o fprintf() is used to write the appended data into the file.
Introduction to Graphics in C
Graphics programming in C enables us to draw images and objects on the screen using pixel-
based operations. Unlike text-based programs, where characters are displayed on a console,
graphics programming manipulates pixels, allowing us to work with visual content like images,
shapes, lines, and color patterns.
In C, graphics mode and text mode refer to different types of displays:
Text Mode: Displays characters on the screen. It is the default mode.
Graphics Mode: Allows you to draw shapes, images, and manipulate pixels directly.
2. Graphics Setup
To use graphics functions, you must first initialize the graphics system and set the graphics
mode. The graphics.h library provides the initgraph() function to do this.
Initialization Steps:
1. Initialize Graphical Mode:
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
o gd is the graphics driver, and gm is the graphics mode. The DETECT constant
helps automatically detect the appropriate driver.
o " " (empty string) is the path to the graphics driver (only necessary for Turbo C).
2. Close Graphical Mode: After completing the graphical operations, you should call
closegraph() to return to text mode.
closegraph();
3. Constants, Data Types, and Global Variables in Graphics
Graphics programming in C uses several constants and variables to handle drawing operations,
colors, and screen dimensions. Here's an overview:
Constants:
1. Color Constants:
o BLACK, WHITE, RED, GREEN, BLUE, etc., are predefined color constants.
Each constant represents a color, with values defined by the graphics library.
2. Screen Coordinates:
o Functions like getmaxx() and getmaxy() return the maximum screen coordinates
(width and height) of the graphics window.
3. Line Styles:
o You can set line styles using setlinestyle(). It allows you to choose between solid
lines, dashed lines, or dotted lines.
Data Types:
int: Used for most graphics operations like coordinates (e.g., (x, y) positions), colors, and
line thickness.
float: Used for more precise control over drawing operations, such as rotation and
transformations.
Global Variables:
Graphics Driver (gd): The graphics driver manages hardware and software
communication to render graphics.
Graphics Mode (gm): Defines the display mode (color, resolution, etc.).
4. Common Graphics Functions
Here are some of the most commonly used graphics functions in C programming:
Initialization and Setup:
initgraph(): Initializes the graphics system.
closegraph(): Closes the graphics system and returns to text mode.
Drawing Functions:
These functions allow you to draw shapes like lines, rectangles, circles, etc.
line(x1, y1, x2, y2):
o Draws a straight line from (x1, y1) to (x2, y2).
Example:
line(100, 100, 200, 200); // Draw a line from (100, 100) to (200, 200)
circle(x, y, radius):
o Draws a circle with the center at (x, y) and a specified radius.
Example:
circle(200, 200, 50); // Draw a circle with radius 50 at (200, 200)
rectangle(x1, y1, x2, y2):
o Draws a rectangle using two opposite corners: (x1, y1) and (x2, y2).
Example:
rectangle(100, 100, 200, 150); // Draw a rectangle with specified corners
ellipse(x, y, start_angle, end_angle, x_radius, y_radius):
o Draws an ellipse with a specified center (x, y), starting and ending angles, and
radii.
Example:
ellipse(200, 200, 0, 360, 100, 50); // Draw a full ellipse with specified radii
Filling Functions:
setfillstyle(pattern, color):
o Sets the fill pattern and color for shapes. The pattern specifies the type of fill (e.g.,
solid, horizontal lines), and the color specifies the fill color.
Example:
setfillstyle(SOLID_FILL, YELLOW); // Set solid yellow color for filling
floodfill(200, 200, WHITE); // Fill an area starting from (200, 200)
floodfill(x, y, boundary_color):
o Fills an enclosed area with the current fill color starting from (x, y) and stops
when it encounters the boundary_color.
Example:
floodfill(200, 200, RED); // Fill the area with the current fill color, stopping at red
Text Functions:
outtextxy(x, y, "text"):
o Displays the text at the specified coordinates (x, y).
Example:
outtextxy(100, 100, "Hello, Graphics!"); // Display text at (100, 100)
Pixel Manipulation:
putpixel(x, y, color):
o Draws a single pixel at coordinates (x, y) with the specified color.
Example:
putpixel(100, 100, BLUE); // Draw a blue pixel at (100, 100)
getpixel(x, y):
o Returns the color of the pixel at the coordinates (x, y).
Example:
int color = getpixel(100, 100); // Get the color of the pixel at (100, 100)
5. Drawing and Filling Images
Graphics in C can involve more complex shapes and even images. The following are examples
of how to fill and manipulate images:
Drawing a Filled Circle:
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Draw a circle with center (200, 200) and radius 50
circle(200, 200, 50);
// Set the fill pattern to solid red and fill the circle
setfillstyle(SOLID_FILL, RED);
floodfill(200, 200, WHITE); // Fill the circle with red color
getch(); // Wait for user input
closegraph(); // Close graphics mode
return 0;
}
6. GUI Interaction within a Program
A simple graphical user interface (GUI) can be implemented using basic drawing and user
interaction methods (like mouse clicks or keyboard input). In a basic graphics program, a GUI
can include buttons, input fields, and other visual elements to interact with the user.
Creating Buttons and Text Boxes:
1. Draw a rectangle for the button.
2. Capture the mouse click event.
3. Perform an action when the button is clicked (e.g., display a message).
7. Important Points to Remember
Always initialize the graphics mode using initgraph().
Set up the appropriate graphics driver and mode before starting to draw.
To exit graphics mode and return to text mode, always use closegraph().
Use the getmaxx() and getmaxy() functions to determine the screen size and place
elements dynamically.
For filling shapes, set the fill style and then use floodfill() to fill areas enclosed by a
boundary.
C Program to Display 50 Concentric Circles
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
int x = 320, y = 240; // Center of the circles (you can adjust this as per your screen size)
int radius = 10; // Starting radius for the first circle
int i;
// Initialize graphics mode
initgraph(&gd, &gm, "");
// Loop to draw 50 concentric circles
for (i = 0; i < 50; i++) {
circle(x, y, radius); // Draw circle with radius
radius += 10; // Increase radius for the next circle
}
getch(); // Wait for a key press
closegraph(); // Close graphics mode
return 0;
}