Unit 5: Dynamic Memory Allocation




Dynamic Memory Allocation in C

Dynamic Memory Allocation (DMA) means:

  • Allocating memory during program execution (runtime) instead of compile-time.
  • Memory is taken from a special area called Heap Memory.
  • Used when the size of data is not known in advance.

Why do we need DMA?

  • For handling large data that may change (user input, arrays, strings).
  • Efficient memory utilization.
  • Flexibility in programs.

DMA Library Required

All DMA functions are available in:

#include <stdlib.h>

malloc() – Memory Allocation

malloc() allocates memory in bytes.

Syntax

ptr = (type*) malloc(size_in_bytes);

Features

  • Allocates continuous block of memory.
  • Memory contains garbage values.
  • Returns a void pointer, so typecasting is required.

Example

int *p; p = (int*) malloc(5 * sizeof(int)); // memory for 5 integers

calloc() – Continuous Allocation

calloc() stands for Contiguous Allocation.

Syntax

ptr = (type*) calloc(num_of_blocks, size_of_each_block);

Features

  • Allocates multiple blocks, each of equal size.
  • Initializes memory with 0 (unlike malloc).
  • Memory is contiguous.

Example

int *p; p = (int*) calloc(5, sizeof(int)); // memory for 5 integers initialized to 0

malloc vs calloc

Featuremalloccalloc
InitializationGarbageInitializes to 0
ParametersSingleTwo
SpeedFasterSlightly slower
Use caseWhen initialization not neededWhen initialization needed

realloc() – Re-allocation

realloc() changes the size of already allocated memory.

Syntax

ptr = (type*) realloc(ptr, new_size);

Features

  • Used to increase or decrease memory size.
  • Useful when size is decided later during program.
  • Keeps old data intact (as much as fits in new size).

Example

p = (int*) malloc(3 * sizeof(int)); p = (int*) realloc(p, 5 * sizeof(int)); // increase size

free() – Release Memory

free() is used to deallocate memory taken by malloc, calloc, or realloc.

Syntax

free(ptr);

Features

  • Prevents memory leakage.
  • Should always be used when memory is no longer needed.

Example: free(p); // frees memory from heap

Example Program Using All DMA Functions

#include <stdio.h> #include <stdlib.h> int main() { int *p; // allocate memory using malloc p = (int*) malloc(3 * sizeof(int)); // reallocate memory p = (int*) realloc(p, 5 * sizeof(int)); // use allocated memory for(int i = 0; i < 5; i++) { p[i] = i + 1; printf("%d ", p[i]); } // free memory free(p); return 0; }

Quick Summary (For Exams)

FunctionUseInitializationMemory From
malloc()Allocate memoryGarbage valuesHeap
calloc()Allocate multiple blocks0Heap
realloc()Change size of allocated memoryDepends on old valuesHeap
free()Release memoryHeap

FILE HANDLING IN C

Normally, data stored in variables disappears when program finishes.
File handling allows us to store data permanently on secondary storage (like hard disk).

Basics of File Handling

File handling means:

  • Creating files
  • Reading from files
  • Writing into files
  • Closing files

Files allow persistent storage of data beyond program execution.

File Types in C

C supports two types of files:

TypeDescription
Text Files (.txt)Human readable, characters stored using ASCII
Binary Files (.bin)Not human readable, faster and more efficient, used for structured data

File Operations

C provides these major file operations:

  1. Create a file
  2. Open a file
  3. Read from a file
  4. Write to a file
  5. Append data to existing file
  6. Close a file
  7. Update / modify
  8. Delete a file (using remove function)

File Pointer in C

A file is controlled using a file pointer, a special pointer of type:

FILE *fp;

It stores:

  • Address of file information
  • Current position in file

All file operations use this pointer.

File Opening Modes

ModeMeaningFile must exist?Pointer position
"r"Open for readingYesBeginning
"w"Open for writing (overwrite)NoBeginning
"a"Open for appendingNoEnd of file
"r+"Read + writeYesBeginning
"w+"Read + write (overwrite)NoBeginning
"a+"Read + writeNoEnd of file
"rb"Read binaryYesBeginning
"wb"Write binaryNoBeginning
"ab"Append binaryNoEnd
"rb+"Read + write binaryYesBeginning
"wb+"Read + write binaryNoBeginning

Example:

FILE *fp; fp = fopen("data.txt", "r");

File Handling Functions

1. fopen() – open a file

fp = fopen("file.txt", "r");

2. fclose() – close a file

fclose(fp);

3. fgetc() – read a single character

char ch = fgetc(fp);

4. fputc() – write a single character

fputc('A', fp);

5. fgets() – read a string

fgets(str, 50, fp);

6. fputs() – write a string

fputs("Hello", fp);

7. fscanf() – formatted read

fscanf(fp, "%d %s", &id, name);

8. fprintf() – formatted write

fprintf(fp, "%d %s\n", id, name);

9. fread() & fwrite() – binary file operations

fread(&emp, sizeof(emp), 1, fp); fwrite(&emp, sizeof(emp), 1, fp);

10. fseek() – move file pointer

fseek(fp, 0, SEEK_SET); // move to beginning

11. ftell() – position of file pointer

long int pos = ftell(fp);

12. rewind() – move pointer to beginning

rewind(fp);

File Handling Through Command Line Arguments

Command line arguments allow the program to accept file names through terminal.

Example:

program.exe input.txt output.txt

C program syntax:

int main(int argc, char *argv[]) { FILE *fp1, *fp2; fp1 = fopen(argv[1], "r"); // input file fp2 = fopen(argv[2], "w"); // output file // Copy content... }

Meaning:

  • argc = number of arguments
  • argv = array of strings (arguments)

Record I/O in Files (Structure Files)

Used when storing records (like student details, employee details).

Writing a record (binary file)

struct student { int roll; char name[20]; float marks; }; struct student s; FILE *fp = fopen("stud.dat", "wb"); fwrite(&s, sizeof(s), 1, fp);

Reading a record

FILE *fp = fopen("stud.dat", "rb"); fread(&s, sizeof(s), 1, fp);

Example: Writing & Reading a Text File

Write

FILE *fp = fopen("test.txt", "w"); fputs("Hello MCA Students", fp); fclose(fp);

Read

FILE *fp = fopen("test.txt", "r"); char str[50]; fgets(str, 50, fp); printf("%s", str); fclose(fp);

SUMMARY TABLE (FOR EXAMS)

TopicKey Points
File PointerFILE *fp used for all file operations
fopen()Opens a file
fclose()Closes a file
fgetc()/fputc()Character I/O
fgets()/fputs()String I/O
fprintf()/fscanf()Formatted I/O
fread()/fwrite()Binary I/O
fseek(), ftell()Pointer movement
Command lineargc, argv[]
Record I/OUse of structures with binary files

GRAPHICS IN C 

C graphics is usually implemented using BGI (Borland Graphics Interface) in the <graphics.h> library.
It is used to draw shapes, lines, text, images and interactive GUI programs.

Introduction to Graphics

Graphics programming in C means using library functions to draw:

  • Lines
  • Circles
  • Rectangles
  • Arcs
  • Polygons
  • Pixels
  • Text

This is done with the help of a special library:

#include <graphics.h>

The functions convert commands into pixel-based drawing on the screen.

Graphics Initialization

Before drawing anything, graphics mode must be initialized.

int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

initgraph()

  • Loads graphics driver

  • Switches screen to graphics mode

Constants Used in Graphics

These constants are predefined in <graphics.h>.

Color Constants

ConstantColor
BLACK0
BLUE1
GREEN2
RED4
WHITE15
YELLOW14
CYAN3

Line Style Constants

ConstantMeaning
SOLID_LINEcontinuous line
DOTTED_LINEdotted
DASHED_LINEdashed
THICK_WIDTHthick

Fill Style Constants

ConstantPattern
SOLID_FILLsolid color
LINE_FILLdiagonal lines
HATCH_FILLcross-hatch
XHATCH_FILLcriss-cross

Data Types and Global Variables in Graphics

Global Variables

Some graphics programs use:

VariableMeaning
gd, gmgraphics driver and mode
MAXCOLORmaximum number of colors
graphresult()stores error code
currentcolor()current drawing color

Important Data Types

  • int → for coordinates (x,y)
  • unsigned int → colors & patterns
  • char* → font names, file paths

Library Functions Used in Drawing

Below are the most important drawing functions:

1. line()

Draws a straight line.

line(x1, y1, x2, y2);

2. rectangle()

rectangle(left, top, right, bottom);

3. circle()

circle(x, y, radius);

4. arc()

arc(x, y, start_angle, end_angle, radius);

5. ellipse()

ellipse(x, y, start_angle, end_angle, x_radius, y_radius);

6. putpixel()

putpixel(x, y, color);

7. drawpoly()

drawpoly(number_of_points, array_of_coordinates);

Filling Shapes (Coloring)

1. setfillstyle()

Selects pattern & color.

setfillstyle(SOLID_FILL, RED);

2. floodfill()

Used to fill a closed shape.

floodfill(x, y, boundary_color);

3. bar()

Draws & fills rectangle.

bar(left, top, right, bottom);

4. setcolor()

Sets current color.

setcolor(YELLOW);

Drawing and Filling Example

#include <graphics.h> #include <conio.h> int main() { int gd = DETECT, gm; initgraph(&gd, &gm, ""); setcolor(RED); rectangle(100, 100, 300, 200); setfillstyle(SOLID_FILL, BLUE); floodfill(150, 150, RED); getch(); closegraph(); return 0; }

GUI Interaction Within the Program

Graphics allows user interaction such as:

1. Detecting Mouse Click

int x = mousex(); int y = mousey();

2. getmouseclick()

getmouseclick(WM_LBUTTONDOWN, x, y);

3. Keyboard Interaction

char ch = getch();

4. Button Design

You can draw simple GUI components:

  • Buttons (rectangles with text)
  • Input boxes
  • Menus
  • Sliders
  • Simple games (car racing, bouncing ball)

Example: Simple Clickable Button

rectangle(100, 100, 200, 150); outtextxy(120, 120, "OK");

You monitor whether the mouse click occurs inside the rectangle.

SUMMARY (FOR EXAMS)

TopicKey Points
Graphics library<graphics.h>
Important functionsline, circle, arc, rectangle, putpixel, bar
Fill functionssetfillstyle, floodfill, bar
Constantscolors, line styles, fill patterns
Global variablesgd, gm
User interactionmouse clicks, keyboard input