Mastering Dynamic Memory in C: malloc, calloc, realloc, free, and memset
This guide explains how to allocate, initialize, resize, and release heap memory in C using malloc, calloc, realloc, free, and memset, with detailed code examples and tips for avoiding memory leaks.
Heap Memory Allocation Functions
#include <stdlib.h>provides the standard allocation functions.
malloc
void *malloc(size_t size);allocates size bytes of uninitialized memory and returns a pointer to the start of the block, or NULL on failure. The returned void* should be cast to the appropriate type.
#include <stdio.h>
#include <stdlib.h>
int main(){
char *pb = (char *)malloc(20);
if (!pb) return 1;
/* use pb */
free(pb);
return 0;
}calloc
void *calloc(size_t nmemb, size_t size);allocates memory for an array of nmemb elements, each size bytes, and initializes all bytes to zero.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n = 5;
int *arr = (int *)calloc(n, sizeof(int));
if (!arr) return 1;
/* arr elements are zero */
free(arr);
return 0;
}realloc
void *realloc(void *ptr, size_t size);changes the size of the memory block pointed to by ptr to size bytes. It returns a new pointer, which may be the same as ptr, or NULL on failure (original block remains valid).
#include <stdio.h>
#include <stdlib.h>
int main(){
int *arr = (int *)malloc(5 * sizeof(int));
if (!arr) return 1;
arr = (int *)realloc(arr, 10 * sizeof(int));
if (!arr) return 1;
for (int i = 0; i < 10; ++i) arr[i] = i;
free(arr);
return 0;
}Memory Initialization
#include <string.h>memset
void *memset(void *s, int c, size_t n);fills the first n bytes of the memory area pointed to by s with the byte value c. Commonly used to zero‑initialize buffers.
#include <stdio.h>
#include <string.h>
int main(){
char buf[10];
memset(buf, 'A', 5); // first 5 bytes become 'A'
buf[5] = '\0';
printf("%s
", buf);
return 0;
}Freeing Memory
#include <stdlib.h> void free(void *ptr);Pass the pointer returned by malloc, calloc or realloc to release the allocated block.
Common Pitfalls and Best Practices
Always pair each allocation with a corresponding free to avoid memory leaks.
Check the return value of allocation functions before using the pointer.
Do not use a pointer after it has been freed.
When resizing with realloc, assign the result to a temporary pointer to avoid losing the original block on failure.
Detecting Memory Leaks
Tools such as Valgrind (dynamic analysis) or static code analyzers can identify unreleased allocations.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
