6. C Dynamic Memory Allocation & File I/O

Comprehensive Guide: Heap memory, malloc, calloc, realloc, free, file pointers, fopen, fprintf & fscanf

Module 1: Dynamic Memory Allocation (malloc, calloc, free)

Allocating RAM memory dynamically on the Heap during program runtime.

🇬🇧 English Definition

Dynamic Memory Allocation allows C programs to request RAM memory from the Heap dynamically at runtime using malloc, calloc, realloc, and release it with free.

🇮🇳 Hinglish Definition

Dynamic Memory Allocation se runtime par Heap memory mangi jati hai. Memory leak se bachne ke liye kaam khatam hote hi free() karna zaroori hai.

Core Concepts & Rules

  • malloc(size): Allocates uninitialized memory block.
  • calloc(n, size): Allocates zero-initialized memory block.
  • free(ptr): Deallocates heap memory back to OS to prevent Memory Leaks.

🔍 Line-by-Line Code Breakdown

  1. Line 2: Allocate integer array of size 3 on Heap using malloc: (int*)malloc(3 * sizeof(int)).
  2. Line 3-5: Assign values to heap memory slots ptr[0], ptr[1], ptr[2].
  3. Line 6: Free heap memory using free(ptr).
💻 Practical C Code Example - Dynamic Memory Allocation (malloc, calloc, free)
int main() {
    int *ptr = (int*)malloc(3 * sizeof(int));
    if (ptr != NULL) {
        ptr[0] = 100; ptr[1] = 200; ptr[2] = 300;
        printf("Heap Memory Allocated: %d, %d, %d\n", ptr[0], ptr[1], ptr[2]);
        free(ptr); // Release memory
    }
    return 0;
}
📤 Compiled Program Output:
Heap Memory Allocated: 100, 200, 300

Module 2: File I/O Operations in C

Reading from and writing data persistently to external disk files.

🇬🇧 English Definition

File I/O in C involves using FILE pointers to open, write, read, and close files on disk storage.

🇮🇳 Hinglish Definition

File I/O se data hard disk ki files me permanent store kiya jata hai taaki program band hone ke baad bhi data safe rahe.

Core Concepts & Rules

  • File Modes: 'w' (write), 'r' (read), 'a' (append).
  • fopen('filename', 'mode') returns FILE pointer.
  • fclose(fp) closes file stream cleanly.

🔍 Line-by-Line Code Breakdown

  1. Line 2: Declare FILE pointer FILE *fp;
  2. Line 3: Open demo.txt in write mode ('w').
  3. Line 4-5: Write text using fprintf and close file with fclose(fp).
💻 Practical C Code Example - File I/O Operations in C
int main() {
    FILE *fp = fopen("notes_demo.txt", "w");
    if (fp != NULL) {
        fprintf(fp, "C Notes \n");
        fclose(fp);
        printf("Data written to notes_demo.txt successfully!\n");
    }
    return 0;
}
📤 Compiled Program Output:
Data written to notes_demo.txt successfully!