Unit 12: Dynamic Memory Management

Contents

1. Introduction to Dynamic Memory Management

Dynamic Memory Management (DMM) is a method in C programming that allows a programmer to allocate or deallocate memory during the execution (runtime) of a program. Unlike static allocation (where memory is fixed at compile time, such as in standard arrays), DMM provides flexibility in handling data whose size may change during program execution.

Key Difference: Static memory is allocated on the Stack, while dynamic memory is allocated on the Heap.

2. Memory Management Functions: malloc, calloc, realloc, free

C provides four standard library functions for dynamic memory management, defined in the <stdlib.h> header file.

1. malloc() - Memory Allocation

The malloc() function allocates a single large block of contiguous memory of a specified size. It returns a void pointer which can be cast into any type.

ptr = (cast_type*) malloc(byte_size);

2. calloc() - Contiguous Allocation

The calloc() function allocates multiple blocks of memory, each of the same size.

ptr = (cast_type*) calloc(n, element_size);

3. realloc() - Re-allocation

The realloc() function is used to change the size of previously allocated memory. It is useful when the initial allocation is insufficient or too large.

ptr = (cast_type*) realloc(ptr, new_byte_size);

4. free() - De-allocation

The free() function is used to manually release the memory allocated by malloc() or calloc(). If memory is not freed, it leads to a Memory Leak.

free(ptr);

3. Pointers and Arrays

There is a very close relationship between pointers and arrays in C. An array name itself acts as a constant pointer to the first element of the array.

Key Concepts:

4. Pointers and Functions

Pointers can be passed to functions as arguments, allowing the function to modify the original variable in memory. This is known as Call by Reference.

Passing Pointers to Functions:

void update(int *p) {
    *p = *p + 10; // Modifies the value at the address stored in p
}
    

Returning Pointers from Functions:

Functions can also return pointers. However, you should never return the address of a local variable because it is destroyed when the function finishes. Always return addresses of static variables or dynamically allocated heap memory.

5. Exam Focus Enhancements

Exam Tips
Common Mistakes
Frequently Asked Questions

Q: What happens if realloc() cannot find a contiguous block of the new size?
A: It will allocate a new block elsewhere, copy the existing data, free the old block, and return the new address.

Q: Why is dynamic memory allocation needed?
A: It allows us to handle data structures like Linked Lists and Trees where the size isn't known until the program runs.

Q: Can free() be used on a static array?
A: No. free() can only be used on pointers that were allocated using the dynamic allocation functions (malloc, calloc, realloc).