Summary - Memory and stack
- C course
- Beginner
- Lesson 105/116
- 5 min
Combine malloc, free and realloc to write a dynamic array.
Summary - Memory and stack
In this group you learned C's memory model. Local variables live on the stack; what you allocate with malloc lives on the heap. Automatic storage needs no free; the heap is yours to manage.
int a = 10; /* stack */
int *p = malloc(sizeof(int)); /* heap */
int *z = calloc(3, sizeof(int));
free(p); free(z); /* release */Every malloc/calloc must have a free; otherwise memory leaks. With realloc you can grow or shrink memory. Now you will do an exercise that combines these concepts.
Practice malloc, use, free: square computation
Allocate an int with malloc; assign *p = 7. Compute its square with (*p) * (*p); print it with printf. Release the memory with free. Include the <stdlib.h> header.
Starter code
#include <stdio.h>
int main(void) {
/* Allocate an int with malloc; *p=7; print its square with printf; release with free */
return 0;
}Sample solution
#include <stdlib.h>
int *p = malloc(sizeof(int));
*p = 7;
int sq = (*p) * (*p);
printf("%d\n", sq);
free(p);Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match function to task
| Term | Meaning |
|---|---|
malloc |
Allocates on heap |
calloc |
Allocates zeroed |
realloc |
Resizes |
free |
Releases |
2 Which memory must be released with free?
- Local variable
- Memory allocated with malloc Correct answer
- Static variable
- Array element
Explanation: Heap memory allocated with malloc/calloc is released with free.
3 Fill in the blank: malloc + sizeof
int *p = ____(sizeof(int));
int *p = malloc(sizeof(int));
Explanation: malloc(sizeof(int)) allocates one int on the heap.