Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

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

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

C Language

  1. How Molybdenum Shapes Modern Industry: Uses, Benefits, and Supply Dynamics
  2. Using Impure Functions in VHDL: Enhancing FSM Readability and Maintainability
  3. Mastering VHDL Functions: A Practical Guide to Efficient Design
  4. A Beginner’s Guide to Perceptron Neural Networks: Classifying Data with a Simple Example
  5. C++ Polymorphism Explained: Practical Examples & Key Concepts
  6. Dynamic Memory Allocation in C: Understanding malloc() with Practical Examples
  7. calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example
  8. Mastering C’s free() Function: Practical Guide & Example
  9. Mastering the 'this' Keyword in Java: Purpose, Usage, and Practical Examples
  10. Master ServoTimer2 Library: Simple Guide to Servo Sweep Control