0
0
Cprogramming~20 mins

free function - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Free Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code using free()?

Consider the following C code snippet. What will be printed when it runs?

C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = malloc(sizeof(int));
    *ptr = 42;
    free(ptr);
    printf("%d\n", *ptr);
    return 0;
}
A0
BCompilation error
C42
DUndefined behavior (likely garbage or crash)
Attempts:
2 left
💡 Hint

Think about what happens to memory after free() is called.

🧠 Conceptual
intermediate
1:30remaining
What does free() do in C?

Which of the following best describes what the free() function does?

ADeallocates previously allocated memory
BCopies memory from one location to another
CAllocates memory on the heap
DInitializes memory to zero
Attempts:
2 left
💡 Hint

Think about how you return memory to the system after using malloc.

🔧 Debug
advanced
2:00remaining
Identify the error related to free() in this code

What error will this code cause when run?

C
#include <stdlib.h>

int main() {
    int x = 10;
    int *ptr = &x;
    free(ptr);
    return 0;
}
ASegmentation fault at malloc
BFreeing memory not allocated by malloc causes undefined behavior
CNo error, runs fine
DDouble free error
Attempts:
2 left
💡 Hint

Consider what kind of pointers can be passed to free().

📝 Syntax
advanced
1:30remaining
Which option correctly frees a dynamically allocated array?

Given int *arr = malloc(5 * sizeof(int));, which option correctly frees the memory?

Afree(arr[0]);
Bfree(&arr);
Cfree(arr); arr = NULL;
Dfree(*arr);
Attempts:
2 left
💡 Hint

Remember what free() expects as its argument.

🚀 Application
expert
2:30remaining
How many times is free() called and what is the output?

Analyze the code below. How many times is free() called and what is printed?

C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *a = malloc(sizeof(int));
    int *b = a;
    *a = 100;
    free(a);
    free(b);
    printf("%d\n", *b);
    return 0;
}
Afree() called twice; causes undefined behavior (likely crash)
Bfree() called twice; prints 100
Cfree() called once; prints 100
Dfree() called once; causes segmentation fault
Attempts:
2 left
💡 Hint

Consider what happens when you free the same memory twice.