🇯🇵 日本語 | 🇺🇸 English
Advertisement

Quiz (Dynamic Memory)

Test your understanding of malloc/free, dangling pointers, memory leaks, and calloc.

Question 1 — malloc basics

int *p = (int *)malloc(sizeof(int) * 3);
p[0] = 10; p[1] = 20; p[2] = 30;
printf("%d\n", p[1]);
free(p);

What does this print?

10
20
30
Compile error
Explanation: malloc(sizeof(int)*3) allocates space for 3 ints on the heap. p[1] is the second element = 20.

Question 2 — Access after free

int *p = (int *)malloc(sizeof(int));
*p = 42;
free(p);
printf("%d\n", *p);

What happens?

42
0
Undefined behavior (dangling pointer)
Compile error
Explanation: Accessing memory through a pointer after free (a dangling pointer) is undefined behavior.
The old value may still appear to be there, but this is not guaranteed. A common safe pattern is to set p = NULL; right after free.

Question 3 — Memory leak

void func(void) {
    int *p = (int *)malloc(sizeof(int) * 100);
    *p = 42;
    // forgot free(p)
}

What's the problem here?

Compile error
Runtime error
Memory leak (runs, but memory is never released)
Nothing is wrong
Explanation: Returning from the function without calling free loses the pointer, so the allocated memory can never be returned to the heap.
This is a memory leak. The program will still run, but calling this repeatedly will exhaust memory.

Question 4 — calloc vs malloc

int *a = (int *)calloc(5, sizeof(int));
printf("%d %d %d\n", a[0], a[2], a[4]);
free(a);

What does this print?

Garbage values
0 0 0
Compile error
Segmentation Fault
Explanation: Unlike malloc, calloc zero-initializes the allocated memory.
So the output is 0 0 0. Use calloc whenever zero-initialization is desired.

Result

Please answer the questions
Home