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:
malloc() – Memory Allocation
malloc() allocates memory in bytes.
Syntax
Features
- Allocates continuous block of memory.
- Memory contains garbage values.
- Returns a void pointer, so typecasting is required.
Example
calloc() – Continuous Allocation
calloc() stands for Contiguous Allocation.
Syntax
Features
- Allocates multiple blocks, each of equal size.
- Initializes memory with 0 (unlike malloc).
- Memory is contiguous.
Example
malloc vs calloc
| Feature | malloc | calloc |
|---|---|---|
| Initialization | Garbage | Initializes to 0 |
| Parameters | Single | Two |
| Speed | Faster | Slightly slower |
| Use case | When initialization not needed | When initialization needed |
realloc() – Re-allocation
realloc() changes the size of already allocated memory.
Syntax
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
free() – Release Memory
free() is used to deallocate memory taken by malloc, calloc, or realloc.
Syntax
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
Quick Summary (For Exams)
| Function | Use | Initialization | Memory From |
|---|---|---|---|
| malloc() | Allocate memory | Garbage values | Heap |
| calloc() | Allocate multiple blocks | 0 | Heap |
| realloc() | Change size of allocated memory | Depends on old values | Heap |
| free() | Release memory | — | Heap |
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:
| Type | Description |
|---|---|
| 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:
- Create a file
- Open a file
- Read from a file
- Write to a file
- Append data to existing file
- Close a file
- Update / modify
- Delete a file (using remove function)
File Pointer in C
A file is controlled using a file pointer, a special pointer of type:
It stores:
- Address of file information
- Current position in file
All file operations use this pointer.
File Opening Modes
| Mode | Meaning | File must exist? | Pointer position |
|---|---|---|---|
"r" | Open for reading | Yes | Beginning |
"w" | Open for writing (overwrite) | No | Beginning |
"a" | Open for appending | No | End of file |
"r+" | Read + write | Yes | Beginning |
"w+" | Read + write (overwrite) | No | Beginning |
"a+" | Read + write | No | End of file |
"rb" | Read binary | Yes | Beginning |
"wb" | Write binary | No | Beginning |
"ab" | Append binary | No | End |
"rb+" | Read + write binary | Yes | Beginning |
"wb+" | Read + write binary | No | Beginning |
Example:
File Handling Functions
1. fopen() – open a file
2. fclose() – close a file
3. fgetc() – read a single character
4. fputc() – write a single character
5. fgets() – read a string
6. fputs() – write a string
7. fscanf() – formatted read
8. fprintf() – formatted write
9. fread() & fwrite() – binary file operations
10. fseek() – move file pointer
11. ftell() – position of file pointer
12. rewind() – move pointer to beginning
File Handling Through Command Line Arguments
Command line arguments allow the program to accept file names through terminal.
Example:
C program syntax:
Meaning:
argc= number of argumentsargv= 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)
Reading a record
Example: Writing & Reading a Text File
Write
Read
SUMMARY TABLE (FOR EXAMS)
| Topic | Key Points |
|---|---|
| File Pointer | FILE *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 line | argc, argv[] |
| Record I/O | Use 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:
The functions convert commands into pixel-based drawing on the screen.
Graphics Initialization
Before drawing anything, graphics mode must be initialized.
initgraph()
-
Loads graphics driver
-
Switches screen to graphics mode
Constants Used in Graphics
These constants are predefined in <graphics.h>.
Color Constants
| Constant | Color |
|---|---|
| BLACK | 0 |
| BLUE | 1 |
| GREEN | 2 |
| RED | 4 |
| WHITE | 15 |
| YELLOW | 14 |
| CYAN | 3 |
Line Style Constants
| Constant | Meaning |
|---|---|
| SOLID_LINE | continuous line |
| DOTTED_LINE | dotted |
| DASHED_LINE | dashed |
| THICK_WIDTH | thick |
Fill Style Constants
| Constant | Pattern |
|---|---|
| SOLID_FILL | solid color |
| LINE_FILL | diagonal lines |
| HATCH_FILL | cross-hatch |
| XHATCH_FILL | criss-cross |
Data Types and Global Variables in Graphics
Global Variables
Some graphics programs use:
| Variable | Meaning |
|---|---|
gd, gm | graphics driver and mode |
MAXCOLOR | maximum number of colors |
graphresult() | stores error code |
currentcolor() | current drawing color |
Important Data Types
int→ for coordinates (x,y)unsigned int→ colors & patternschar*→ font names, file paths
Library Functions Used in Drawing
Below are the most important drawing functions:
1. line()
Draws a straight line.
2. rectangle()
3. circle()
4. arc()
5. ellipse()
6. putpixel()
7. drawpoly()
Filling Shapes (Coloring)
1. setfillstyle()
Selects pattern & color.
2. floodfill()
Used to fill a closed shape.
3. bar()
Draws & fills rectangle.
4. setcolor()
Sets current color.
Drawing and Filling Example
GUI Interaction Within the Program
Graphics allows user interaction such as:
1. Detecting Mouse Click
2. getmouseclick()
3. Keyboard Interaction
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
You monitor whether the mouse click occurs inside the rectangle.
SUMMARY (FOR EXAMS)
| Topic | Key Points |
|---|---|
| Graphics library | <graphics.h> |
| Important functions | line, circle, arc, rectangle, putpixel, bar |
| Fill functions | setfillstyle, floodfill, bar |
| Constants | colors, line styles, fill patterns |
| Global variables | gd, gm |
| User interaction | mouse clicks, keyboard input |