Using realloc() in C: Syntax, Best Practices & Example
What is realloc()
realloc() is a C standard library function that resizes an existing memory block. It expands or shrinks the block while preserving its content. This makes dynamic memory management more efficient, especially when the required size changes during runtime.
Syntax
ptr = realloc(ptr, newSize);
Here, ptr points to a previously allocated block, and newSize is the desired size in bytes. After the call, ptr will point to the first byte of the new block. The function copies the original data to the new location and frees the old block if the reallocation succeeds.
Key Points to Remember
- When
realloc()succeeds, the returned pointer may be the same as the original or a new address. - If the function fails, it returns
NULLand leaves the original block untouched. - Always assign the result to a temporary pointer to avoid losing the original address on failure.
- After a successful reallocation, free the pointer only once.
Example – Resizing a String Buffer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *buf = malloc(10);
if (!buf) {
perror("malloc");
return EXIT_FAILURE;
}
strcpy(buf, "Programming");
printf("%s\n", buf);
char *tmp = realloc(buf, 20); // increase buffer size
if (!tmp) {
free(buf); // original block still valid
perror("realloc");
return EXIT_FAILURE;
}
buf = tmp;
strcat(buf, " in C");
printf("%s\n", buf);
free(buf);
return EXIT_SUCCESS;
}
Example – Allocating and Resizing an Integer Array
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *arr = malloc(10 * sizeof(int));
if (!arr) {
perror("malloc");
return EXIT_FAILURE;
}
/* ... use the array ... */
int *tmp = realloc(arr, 50 * sizeof(int));
if (!tmp) {
free(arr);
perror("realloc");
return EXIT_FAILURE;
}
arr = tmp;
printf("Array resized successfully\n");
free(arr);
return EXIT_SUCCESS;
}
Practical Tips
- Prefer
size_tfor size arguments to avoid sign‑related bugs. - When shrinking a block, be aware that data beyond the new size is discarded.
- Always check the return value before using the pointer.
- Use
free()exactly once for each successful allocation.
C Language
- How Molybdenum Shapes Modern Industry: Uses, Benefits, and Supply Dynamics
- Using Impure Functions in VHDL: Enhancing FSM Readability and Maintainability
- Mastering VHDL Functions: A Practical Guide to Efficient Design
- A Beginner’s Guide to Perceptron Neural Networks: Classifying Data with a Simple Example
- C++ Polymorphism Explained: Practical Examples & Key Concepts
- Dynamic Memory Allocation in C: Understanding malloc() with Practical Examples
- calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example
- Mastering C’s free() Function: Practical Guide & Example
- Mastering the 'this' Keyword in Java: Purpose, Usage, and Practical Examples
- Master ServoTimer2 Library: Simple Guide to Servo Sweep Control