Sub topic 13
Dynamic memory: malloc, calloc, realloc, free
This chapter assumes you can read pointer declarations, know that sizeof yields a size_t, and understand that local variables live on the call stack. It covers the four standard allocation functions in <stdlib.h>, their exact behavior, and the traps that GATE questions use.
Why the heap exists
Local variables live in a stack frame and disappear when the function returns. Their size is also fixed at compile time. Dynamic allocation fixes both limits. You request a block of bytes at run time, and the block stays valid until you release it, whichever function created it.
The memory comes from the heap, a region managed by the C library. The functions return a void *, a generic pointer that converts to any object pointer type without a cast in C.
| Function | Signature | Initializes memory? | Notes |
|---|---|---|---|
| `malloc` | `void *malloc(size_t size)` | No, contents are indeterminate | One size argument in bytes |
| `calloc` | `void *calloc(size_t n, size_t size)` | Yes, all bytes set to zero | Checks `n * size` for overflow |
| `realloc` | `void *realloc(void *p, size_t size)` | Old bytes kept, new bytes indeterminate | May move the block |
| `free` | `void free(void *p)` | Not applicable | `free(NULL)` does nothing |
malloc
malloc returns a pointer to at least size bytes, or NULL if the request fails. Always check for NULL before using the result.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
int *a = malloc(n * sizeof *a);
if (a == NULL) {
return 1;
}
for (int i = 0; i < n; i++) {
a[i] = i * i;
}
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
free(a);
return 0;
}This prints 0 1 4 9 16. The idiom malloc(n * sizeof *a) is preferred over malloc(n * sizeof(int)). If you later change the type of a, the size stays correct automatically. sizeof *a is not evaluated, so the unassigned pointer is not dereferenced.
Reading a[i] before writing it is a bug. malloc does not clear memory, so the value is indeterminate.
calloc
calloc(n, size) allocates room for n elements of size bytes each and sets every byte to zero. For integer types this gives value 0. On common platforms, all-bits-zero also means 0.0 for floating types and a null pointer for pointer types. The C standard guarantees only the integer case.
calloc also protects against overflow. If n * size exceeds what size_t can hold, calloc returns NULL. An expression such as malloc(n * size) instead wraps around silently and returns a block that is too small.
realloc
realloc(p, new_size) resizes a block that came from malloc, calloc, or an earlier realloc. Its rules matter for exam questions:
- If it succeeds, the first
min(old, new)bytes are preserved. The block may have moved, and the old pointer is then invalid. Use only the returned pointer. - If it fails, it returns
NULLand the original block is left untouched and still allocated. realloc(NULL, n)behaves likemalloc(n).
Because of the failure rule, the line p = realloc(p, n); is a classic bug. On failure, p becomes NULL and the original block is leaked. Use a temporary pointer.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = calloc(3, sizeof *a);
if (a == NULL) {
return 1;
}
for (int i = 0; i < 3; i++) {
a[i] = i + 1;
}
int *tmp = realloc(a, 6 * sizeof *tmp);
if (tmp == NULL) {
free(a);
return 1;
}
a = tmp;
for (int i = 3; i < 6; i++) {
a[i] = i + 1;
}
for (int i = 0; i < 6; i++) {
printf("%d ", a[i]);
}
printf("\n");
free(a);
return 0;
}This prints 1 2 3 4 5 6. The first three values survive the resize. The last three slots were indeterminate until the second loop wrote them.
free
free(p) returns a block to the heap. It requires that p is either NULL or exactly a pointer returned by an allocation function and not yet freed. Three things follow:
freedoes not changep. The pointer still holds the old address, which now points to memory you no longer own. This is a dangling pointer.- Freeing the same block twice (a double free) is undefined behavior.
- Freeing a pointer that did not come from the heap is undefined behavior. Examples are
free(&x)andfree(p + 1).
Setting p = NULL after free(p) is a common defensive habit. A later free(p) then does nothing, and a later dereference usually crashes at once instead of corrupting data.
Stack versus heap lifetime
A frequent exam trap is returning the address of a local variable. The frame is destroyed on return, so the pointer is dangling. A heap block avoids this because its lifetime is independent of the function that made it.
Points GATE likes to test
sizeofon a pointer returned bymallocgives the pointer size, not the block size. The C language has no way to ask a pointer how many bytes it refers to.malloc(sizeof p)wherepisint *allocates the size of a pointer (commonly 8 bytes), not the size of an int. Writesizeof *p.- Pointer arithmetic on the returned pointer scales by the pointee type, as in earlier chapters.
p + 1moves bysizeof *pbytes. malloc(0)may returnNULLor a unique pointer. Either is allowed, and the result must not be dereferenced.- Failure to allocate is reported by
NULL, not by an exception or a crash. - Use of memory after
free, reading uninitializedmallocmemory, and writing past the end of a block are all undefined behavior. Questions often say "the behavior is undefined" as the correct option.
Exercise
A program runs int *p = malloc(4 * sizeof *p);, stores values in p[0] to p[3], then runs p = realloc(p, 8 * sizeof *p);. Give two distinct problems that this realloc line can cause, and write the safe replacement.
Show answer
(1) If realloc fails it returns NULL, so p is overwritten and the original block is leaked. (2) Without a NULL check the program may dereference NULL afterward. Also, if realloc moves the block, any other pointer into the old block (for example int *q = &p[1];) dangles. Safe form: int *tmp = realloc(p, 8 * sizeof *tmp); if (tmp == NULL) { /* handle error; p is still valid */ } else { p = tmp; }.
Exercise
After int *p = malloc(sizeof *p); *p = 7; free(p);, which of these is defined behavior: (a) free(p); again, (b) printf("%d", *p);, (c) p = NULL; free(p);?
Show answer
Only (c). (a) is a double free and (b) reads freed memory, both undefined. After p = NULL, free(p) is guaranteed to do nothing.