TutorialsCMemory Management
Share:

Memory Management

advanced

Part of Advanced C

Theory

C gives the programmer direct control over memory. Understanding stack vs heap, the malloc/calloc/realloc/free functions, and memory leak prevention is essential for writing robust C programs.

Stack vs Heap

| Feature | Stack | Heap | |---------|-------|------| | Allocation | Automatic (function calls) | Manual (malloc/free) | | Speed | Very fast | Slower | | Size | Limited (typically ~8 MB) | Large (RAM limit) | | Lifetime | Function scope | Until explicitly freed | | Management | Compiler handles it | Programmer handles it |

Dynamic Memory Functions

  • malloc(size) — allocates size bytes, returns uninitialized memory
  • calloc(n, size) — allocates n elements of size bytes each, zero-initialized
  • realloc(ptr, newSize) — resizes previously allocated memory
  • free(ptr) — deallocates memory, preventing leaks

Best Practices

Always check if malloc/calloc returns NULL. Always pair every allocation with a free(). After freeing, set the pointer to NULL to prevent dangling pointers.

Practical Examples

Example 1: malloc and free
c
Example 2: calloc and realloc
c

Exercises

Dynamic Student Grades

medium

Write a C program that asks the user for the number of students, dynamically allocates an array of that size using malloc(), reads grades into the array, calculates the average, and frees the memory.

Starter Code:

#include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n  int n;\n  // Your code here\n  return 0;\n}

Expected Output:

Enter number of students: 3\nEnter grade 1: 85\nEnter grade 2: 90\nEnter grade 3: 78\nAverage: 84.33

Mini Quiz

Mini Quiz