Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
c

How to use realloc() in C

Dario Vincenzo Tarantini

In C, we can use the realloc() function to resize previously allocated memory areas at a later time.

This function is included in the <stdlib.h> library.

Syntax

The syntax of the function is as follows:

void *realloc(void *ptr, size_t size);

Parameters

The function needs:

  • **(void *ptr): A pointer that represents the pointer to the beginning of the memory area that you want to resize.
  • (size_t size): The new size of the block in bytes, where size_t is just an alias of unsigned int, defined in the <stdlib.h> library. The new block can be smaller or larger than the one that is being modified.

Return value

The function returns a pointer to the beginning of the block of memory. If the block of memory cannot be allocated, the function will return a null pointer.

Code

Let’s see two examples:

  • The first one assumes that the size of the block to be reallocated is smaller than previously allocated.

  • The second one assumes that the size of the block to be reallocated is bigger than previously allocated.

Example 1

The size of the block is smaller.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *ptr;

    //Here, we allocate memory for 40 integers
    ptr = malloc(10 * sizeof(int));
    ptr[3] = -120;

    //We reallocate memory size to store 16 integers
    ptr = realloc(ptr, 4 * sizeof(int));
    if(ptr == NULL) {
        exit(0);
	}
    // we can still see at address 3
    printf("%d", ptr[3]);
    return 0;
}

Example 2

The size of the block is bigger.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *ptr;

    //Here, we allocate memory for 40 integers
    ptr = malloc(10 * sizeof(int));

    //We reallocate memory size to store 160 integers
    ptr = realloc(ptr, 40 * sizeof(int));
    if(ptr == NULL) {
        exit(0);
	}

    ptr[100] = -120;

    printf("%d", ptr[100]);
    return 0;
}

RELATED TAGS

communitycreator
c

CONTRIBUTOR

Dario Vincenzo Tarantini
RELATED COURSES

View all Courses

Keep Exploring