0
0
Cprogramming~20 mins

Memory allocation flow - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Memory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of malloc and free usage
What is the output of this C program that allocates and frees memory?
C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = (int *)malloc(sizeof(int));
    if (ptr == NULL) {
        printf("Allocation failed\n");
        return 1;
    }
    *ptr = 42;
    printf("Value: %d\n", *ptr);
    free(ptr);
    return 0;
}
AValue: 42
BValue: 0
CSegmentation fault
DCompilation error
Attempts:
2 left
💡 Hint
Remember malloc returns a pointer to allocated memory which you can use before freeing it.
🧠 Conceptual
intermediate
1:30remaining
Understanding realloc behavior
What happens when you call realloc with a NULL pointer in C?
AIt frees the memory and returns NULL.
BIt causes a segmentation fault.
CIt behaves like malloc and allocates new memory.
DIt returns the original pointer without changes.
Attempts:
2 left
💡 Hint
Think about realloc's behavior when given a NULL pointer.
🔧 Debug
advanced
2:30remaining
Identify the cause of memory leak
What causes the memory leak in this code snippet?
C
#include <stdlib.h>

void func() {
    int *arr = malloc(10 * sizeof(int));
    arr = malloc(20 * sizeof(int));
    free(arr);
}
AThere is no memory leak; code is correct.
BThe first malloc'd memory is overwritten without free, causing a leak.
Cfree is called twice on the same pointer.
DThe second malloc is invalid and causes a crash.
Attempts:
2 left
💡 Hint
Look at what happens to the pointer after the first malloc.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in memory allocation
Which option contains a syntax error in memory allocation?
C
int *ptr = malloc(sizeof(int) * 5);
Aint *ptr = malloc(sizeof(int) * 5);
Bint *ptr = (int *)malloc(sizeof(int) * 5);
Cint *ptr = malloc(sizeof(int) * 5);;
Dint *ptr = malloc(sizeof(int) * 5)
Attempts:
2 left
💡 Hint
Check for missing semicolons or extra characters.
🚀 Application
expert
3:00remaining
Predict the number of allocated blocks
After running this code, how many distinct memory blocks are allocated and not freed?
C
#include <stdlib.h>

int main() {
    int *a = malloc(10 * sizeof(int));
    int *b = malloc(5 * sizeof(int));
    free(a);
    a = malloc(20 * sizeof(int));
    int *c = realloc(b, 15 * sizeof(int));
    return 0;
}
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Count allocations minus frees carefully, consider realloc behavior.