Back to course

Dynamic Memory Management: realloc() and free()

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 39: Dynamic Memory Management: realloc() and free()

Proper memory management involves both allocation and deallocation.

3. free() (Memory Deallocation)

Releases the dynamically allocated memory back to the heap, preventing memory leaks. You must call free() exactly once for every successful call to malloc, calloc, or realloc.

Syntax: free(pointer_to_allocated_block);

c int *p = (int *) malloc(sizeof(int)); *p = 50;

// Use the memory...

free(p); // After free(p), p is a dangling pointer (it still holds the old address), // so it is good practice to set it to NULL. p = NULL;

4. realloc() (Memory Reallocation)

Changes the size of the memory block pointed to by the given pointer. It can either expand or shrink the block. The contents of the block are preserved up to the lesser of the new and old sizes.

Syntax: (type *) realloc(old_pointer, new_size_in_bytes);

c int *data = (int *) malloc(5 * sizeof(int)); // Initially size 5 // ... populate data ...

// Reallocate to hold 10 integers int *temp = (int *) realloc(data, 10 * sizeof(int));

if (temp != NULL) { data = temp; // Update the pointer to the new memory location }

Crucial: If realloc fails, it returns NULL but does not free the original block. Always assign the result of realloc to a temporary pointer first.