Recall & Review
beginner
What is the purpose of the
realloc function in C?The
realloc function changes the size of a previously allocated memory block. It can increase or decrease the size without losing the existing data up to the minimum of old and new sizes.Click to reveal answer
intermediate
What happens if
realloc cannot enlarge the existing memory block in place?If
realloc cannot extend the current block, it allocates a new block of the requested size, copies the old data to the new block, frees the old block, and returns a pointer to the new block.Click to reveal answer
intermediate
What does
realloc(ptr, 0) do?Calling
realloc with size 0 is implementation-defined: it may either free the memory pointed to by ptr and return NULL, or return a unique pointer that should not be dereferenced.Click to reveal answer
intermediate
How should you safely use
realloc to avoid memory leaks?Always assign the result of
realloc to a temporary pointer first. If it returns NULL, the original pointer is still valid. Only update the original pointer if realloc succeeds.Click to reveal answer
beginner
What header file must be included to use
realloc?You must include
<stdlib.h> to use the realloc function in C.Click to reveal answer
What does
realloc do if the new size is smaller than the old size?✗ Incorrect
realloc reduces the block size and preserves the data up to the new smaller size.
If
realloc fails to allocate new memory, what happens to the original pointer?✗ Incorrect
The original pointer remains valid if realloc fails; only the returned pointer is NULL.
Which header file is required to use
realloc?✗ Incorrect
realloc is declared in <stdlib.h>.
What is the correct way to avoid losing the original pointer when using
realloc?✗ Incorrect
Using a temporary pointer prevents losing the original pointer if realloc fails.
What does
realloc(NULL, size) do?✗ Incorrect
Passing NULL to realloc behaves like malloc and allocates new memory.
Explain how the
realloc function works and when you would use it.Think about changing the size of a box without losing what is inside.
You got /4 concepts.
Describe the safe way to use
realloc to avoid memory leaks or losing data.Imagine you want to move your stuff to a bigger box but keep the old box until the new one is ready.
You got /4 concepts.