The malloc() and free() Functions
What you'll learn: How to request and release dynamic memory at runtime using C's fundamental heap allocation functions.
The Core Idea
In C, malloc() (memory allocate) and free() are your tools for manual heap memory management. When you need memory whose size or lifetime can't be determined at compile time, you ask the operating system for a chunk of heap memory using malloc(). When you're done with it, you must return that memory using free().
Think of malloc() like renting storage space: you specify how many bytes you need, and if available, you get a pointer to that space. The memory remains yours until you explicitly return it with free().
Using malloc()
int *numbers = (int *)malloc(5 * sizeof(int));
Here, malloc() receives the number of bytes needed (5 integers) and returns a pointer to that memory block. The cast (int *) converts malloc()'s generic void * return type to the appropriate pointer type. If allocation fails (out of memory), malloc() returns NULL.
Always check for NULL before using allocated memory:
if (numbers == NULL) {
// Handle allocation failure
}
Using free()
When you're finished with dynamically allocated memory, release it:
free(numbers);
numbers = NULL; // Good practice: avoid dangling pointer
free() tells the system, "I'm done with this memory—you can reuse it." Never use memory after freeing it, and never free the same pointer twice (both cause undefined behavior).
Key Takeaway: malloc() requests heap memory and returns a pointer to it; free() releases that memory back to the system. Always pair every malloc() with exactly one free() to avoid memory leaks and crashes.