Consider the following C code snippet. What will be printed when it runs?
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = malloc(sizeof(int)); *ptr = 42; free(ptr); printf("%d\n", *ptr); return 0; }
Think about what happens to memory after free() is called.
After calling free(ptr), the memory pointed to by ptr is released back to the system. Accessing *ptr after free() causes undefined behavior, which may print garbage, cause a crash, or anything unpredictable.
Which of the following best describes what the free() function does?
Think about how you return memory to the system after using malloc.
The free() function releases memory that was previously allocated by malloc(), calloc(), or realloc(). It does not allocate or initialize memory.
What error will this code cause when run?
#include <stdlib.h> int main() { int x = 10; int *ptr = &x; free(ptr); return 0; }
Consider what kind of pointers can be passed to free().
free() must only be called on pointers returned by malloc, calloc, or realloc. Here, ptr points to a local variable on the stack, so calling free(ptr) causes undefined behavior.
Given int *arr = malloc(5 * sizeof(int));, which option correctly frees the memory?
Remember what free() expects as its argument.
free() expects a pointer to the start of the allocated memory block. Option C correctly frees arr and then sets it to NULL to avoid dangling pointer. Options A, B, and C pass invalid pointers causing errors or undefined behavior.
Analyze the code below. How many times is free() called and what is printed?
#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; }
Consider what happens when you free the same memory twice.
free() is called twice on the same pointer (a and b point to the same memory). Double free causes undefined behavior, often a crash. Accessing *b after free is also invalid.