Recall & Review
beginner
What is the purpose of the
free function in C?The
free function releases memory that was previously allocated with malloc, calloc, or realloc. It helps prevent memory leaks by returning the memory back to the system.Click to reveal answer
intermediate
What happens if you call
free on a pointer that was not allocated dynamically?Calling
free on a pointer not allocated by malloc or similar functions causes undefined behavior. This can crash the program or corrupt memory.Click to reveal answer
intermediate
Can you use
free more than once on the same pointer without reassigning it?No. Using
free multiple times on the same pointer without resetting it to NULL leads to undefined behavior, often causing crashes or memory corruption.Click to reveal answer
beginner
Show a simple example of allocating and freeing memory for an integer in C.
Example:<br>
int *p = malloc(sizeof(int));
if (p != NULL) {
*p = 10;
free(p);
}<br>This allocates memory for one integer, assigns 10, then frees the memory.Click to reveal answer
intermediate
Why is it important to set a pointer to NULL after calling
free?Setting a pointer to NULL after
free avoids accidental use of a pointer that points to freed memory, which can cause bugs or crashes.Click to reveal answer
What does the
free function do in C?✗ Incorrect
free releases memory allocated by malloc or similar functions.
What happens if you call
free on a pointer twice without resetting it?✗ Incorrect
Double freeing causes undefined behavior and can crash the program.
Which pointer should you pass to
free?✗ Incorrect
Only pointers from dynamic memory allocation functions should be freed.
What is a good practice after calling
free on a pointer?✗ Incorrect
Setting the pointer to NULL prevents accidental use of freed memory.
If
malloc fails and returns NULL, what happens if you call free on that NULL pointer?✗ Incorrect
Calling free on NULL is safe and does nothing.
Explain how the
free function works and why it is important in C programming.Think about memory management and what happens if you don't free memory.
You got /4 concepts.
Describe common mistakes when using
free and how to avoid them.Consider what can cause crashes or bugs related to freeing memory.
You got /4 concepts.