The realloc function helps you change the size of a memory block you already reserved. It lets you grow or shrink your memory without losing the data you stored.
realloc function
void *realloc(void *ptr, size_t new_size);
If ptr is NULL, realloc works like malloc.
If new_size is zero, behavior depends on the system; it may free the memory and return NULL or return a unique pointer that can be freed.
malloc.int *arr = realloc(NULL, 5 * sizeof(int));
arr = realloc(arr, 10 * sizeof(int));
arr = realloc(arr, 3 * sizeof(int));
This program starts with an array of 3 integers, then uses realloc to increase its size to 5. It adds two more numbers and prints all 5.
#include <stdio.h> #include <stdlib.h> int main() { int *numbers = malloc(3 * sizeof(int)); if (numbers == NULL) { printf("Memory allocation failed\n"); return 1; } // Initialize array for (int i = 0; i < 3; i++) { numbers[i] = i + 1; } // Resize array to hold 5 integers int *temp = realloc(numbers, 5 * sizeof(int)); if (temp == NULL) { printf("Reallocation failed\n"); free(numbers); return 1; } numbers = temp; // Add new values numbers[3] = 4; numbers[4] = 5; // Print all values for (int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } printf("\n"); free(numbers); return 0; }
Always check if realloc returns NULL to avoid losing your original memory pointer.
If realloc fails, the original memory block remains valid and must be freed later.
Using realloc can move the memory block to a new location, so always assign its return value back to your pointer.
realloc changes the size of a memory block while keeping its data.
Use it to grow or shrink dynamic arrays or buffers.
Always check for NULL to handle memory errors safely.
Practice
realloc function do in C programming?Solution
Step 1: Understand the purpose of realloc
Thereallocfunction is used to resize an existing memory block allocated bymallocorcalloc.Step 2: Check data preservation behavior
reallocpreserves the existing data up to the minimum of old and new sizes.Final Answer:
It changes the size of a previously allocated memory block, preserving its content. -> Option CQuick Check:
realloc resizes memory and keeps data [OK]
- Thinking realloc frees memory without resizing
- Assuming realloc always allocates new memory without preserving data
- Confusing realloc with memcpy or free
ptr to hold 50 integers using realloc?Solution
Step 1: Understand realloc parameters
realloctakes a pointer and the new size in bytes. To hold 50 integers, size must be 50 times size of int.Step 2: Check each option's correctness
ptr = realloc(ptr, 50 * sizeof(int)); correctly multiplies 50 bysizeof(int). Others misuse parameters or sizes.Final Answer:
ptr = realloc(ptr, 50 * sizeof(int)); -> Option AQuick Check:
Size in bytes = count * sizeof(type) [OK]
- Passing count instead of bytes as size
- Swapping parameters in realloc
- Forgetting sizeof(int) when resizing
int *arr = malloc(3 * sizeof(int));
arr[0] = 1; arr[1] = 2; arr[2] = 3;
arr = realloc(arr, 5 * sizeof(int));
arr[3] = 4; arr[4] = 5;
for(int i = 0; i < 5; i++) printf("%d ", arr[i]);
free(arr);Solution
Step 1: Analyze memory allocation and initialization
Initially, 3 integers allocated and set to 1, 2, 3. Then resized to hold 5 integers.Step 2: Assign new values and print
After realloc, elements 3 and 4 are assigned 4 and 5. Printing all 5 elements outputs 1 2 3 4 5.Final Answer:
1 2 3 4 5 -> Option BQuick Check:
realloc preserves old data and new elements assigned [OK]
- Assuming new elements are zeroed automatically
- Expecting garbage values without assignment
- Thinking realloc frees old data immediately
int *ptr = malloc(10 * sizeof(int));
ptr = realloc(ptr, 20 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
free(ptr);
}Solution
Step 1: Understand realloc return and NULL check
Ifreallocreturns NULL, original pointer is lost if not saved separately, and ptr becomes NULL.Step 2: Analyze free(ptr) after NULL assignment
Callingfree(ptr)after ptr is NULL does not free the original memory block, leading to memory leak.Final Answer:
Calling free(ptr) after ptr is NULL does not free the original memory block. -> Option AQuick Check:
Check realloc result before overwriting pointer [OK]
- Not checking realloc return before assignment
- Freeing NULL pointer thinking it frees old memory
- Ignoring malloc failure before realloc
malloc. You want to safely double its size using realloc without losing data or causing memory leaks. Which approach is correct?Solution
Step 1: Understand safe realloc usage
Directly assigning realloc result to original pointer risks losing original memory if realloc fails.Step 2: Use temporary pointer to check realloc success
Assign realloc to temp pointer, check if not NULL, then update original pointer. Else handle error safely.Final Answer:
int *temp = realloc(ptr, 2 * current_size); if (temp) ptr = temp; else handle error; -> Option DQuick Check:
Use temp pointer to avoid memory leaks on realloc failure [OK]
- Overwriting pointer before checking realloc result
- Freeing pointer before realloc causing data loss
- Not handling realloc failure properly
Ready to prove it?
Pass the test and this pattern moves unknown
