Which function is used to reallocate memory in C?
A
resize() B
realloc() C
reassign() D
realocate()
Analysis & Theory
`realloc()` is used to change the size of memory previously allocated with `malloc()` or `calloc()`.
What happens to the old data when `realloc()` increases the size?
A
It is lost B
It is copied to the new block C
It is reversed D
It causes an error
Analysis & Theory
Old data is preserved (copied) to the new memory location if necessary.
What happens if the new size in `realloc(ptr, newSize)` is smaller than the original?
A
Error B
Data is reallocated and may be truncated C
Nothing happens D
Memory size increases
Analysis & Theory
The memory is resized; extra memory may be lost, and truncation may occur.
What happens if `realloc()` fails to allocate memory?
A
Returns 0 B
Returns garbage C
Returns NULL without freeing the original pointer D
Frees the original memory
Analysis & Theory
`realloc()` returns `NULL` on failure, and the original pointer remains valid.
Which header file is required to use `realloc()`?
A
malloc.h B
stdio.h C
string.h D
stdlib.h
Analysis & Theory
`realloc()` is declared in the `stdlib.h` header.
What is the best way to safely use `realloc()`?
A
Directly overwrite the original pointer B
Store the result in a temporary pointer C
Use `free()` first, then `malloc()` D
Avoid using `realloc()`
Analysis & Theory
Store `realloc()` result in a temporary pointer to avoid losing original memory if reallocation fails.
What does `realloc(ptr, 0)` do?
A
Allocates zero memory B
Does nothing C
Frees the memory D
Returns original pointer
Analysis & Theory
`realloc(ptr, 0)` is equivalent to `free(ptr)` in C.
Can you use `realloc()` on a NULL pointer?
A
No B
Yes, it behaves like malloc() C
Only after `free()` D
Only for arrays
Analysis & Theory
Yes, `realloc(NULL, size)` behaves like `malloc(size)`.
Which is the correct use of `realloc()`?
A
int *p = realloc(10); B
int *p = realloc(p, sizeof(int) * 20); C
realloc(p, int); D
p = realloc(sizeof(int) * 10);
Analysis & Theory
You must pass the old pointer and the new size: `realloc(p, sizeof(int) * n);`
What should you do after calling `realloc()`?
A
Immediately `free()` the pointer B
Check if return value is NULL before using it C
Assume it worked and use the memory D
Use `memcpy()`
Analysis & Theory
Always check if `realloc()` returned `NULL` before using the result.