C Memory Management

C Tutorial

1. C Memory Management

In C Memory Management programs use two main types of memory:

Memory TypeDescription
StackStores local variables, function calls, and automatic data. Managed automatically.
HeapStores dynamically allocated memory. Managed manually using malloc/free.

2. Static vs Dynamic Memory Allocation

TypeDescriptionExample
StaticMemory size known at compile time. Allocated automatically on stack.int a[10];
DynamicMemory size determined at runtime. Allocated manually on heap.malloc(), calloc()

3. Dynamic Memory Allocation Functions

C provides the following functions in <stdlib.h>:

FunctionDescription
malloc(size_t size)Allocates memory of given size in bytes. Returns void*.
calloc(size_t n, size_t size)Allocates memory for n elements, initializes to 0.
realloc(void *ptr, size_t size)Resizes previously allocated memory.
free(void *ptr)Frees memory allocated on heap.

4. Example: Using malloc


 

Output:

1 2 3 4 5

5. Example: Using calloc


 

Output:

0 0 0 0 0

6. Example: Using realloc


 

Output:

1 2 3 4 5

7. Memory Leaks

  • Memory leak occurs when allocated memory is not freed.

  • Always use free() after dynamic allocation.

  • Example:



8. Key Points About C Memory Management

  1. Stack memory: automatic, fast, limited size.

  2. Heap memory: manual, dynamic, larger but slower.

  3. Use malloc, calloc, realloc for dynamic allocation.

  4. Use free() to release heap memory.

  5. Avoid memory leaks by freeing allocated memory.

  6. Proper memory management is crucial in embedded systems, large applications, and performance-critical programs.

You may also like...