malloc allocates raw bytes on the heap. You are responsible for calling free exactly once when done—unlike stack memory or Java GC.
Safe allocation pattern
int *arr = malloc(n * sizeof *arr);
if (arr == NULL) {
/* handle failure */
}
/* use arr */
free(arr);
arr = NULL;
Always check for NULL. Set pointer to NULL after free to avoid double-free mistakes.
Related functions
calloc— zero-initialized allocationrealloc— resize existing block (may move memory)
Important interview questions and answers
- Q: Memory leak?
A: Allocated heap memory never freed—program keeps consuming RAM. - Q: Double free?
A: Callingfreetwice on the same pointer—undefined behavior, often exploitable. - Q: Why sizeof *ptr in malloc?
A: Keeps element size correct if the pointer type changes.
Self-check
- What should you do if malloc returns NULL?
- How many times may you free the same pointer?
Tip: Every malloc needs a matching free on all paths—including early returns and error branches. Set pointer to NULL after free.
Interview prep
- Memory leak?
Allocated heap memory never freed—the process retains RAM until exit.
- Double free?
Calling
freetwice on the same pointer—undefined behavior, often exploitable.- Why check malloc return?
Allocation can fail under memory pressure; dereferencing NULL is undefined behavior.