realloc Function

Changes the size of an allocated block of memory.




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


pointer to object to deallocate
number of byte to allocate

Return Value

Returns a pointer to the allocated space if successful; otherwise, returns a null pointer.


The function deallocates the memory consumed by the object pointed to by ptr and returns a pointer to a new object with the specified size and with the same contents of the old object prior to deallocation, up to the lesser of the previous and new sizes. If the size of the new object is larger than that of the previous object, the additional bytes have indeterminate values.

When using the simple implementation of dynamic memory allocation, reallocating memory will always result in a new allocation being made, regardless of the size of the new memory block.

If ptr is a null pointer, a call to realloc() behaves like one to malloc() with the specified size. The value of ptr must otherwise match a pointer returned by the calloc(), malloc(), or realloc() function, and the memory at that address must not have been deallocated by a call to the free() or realloc() function; otherwise, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

See your MPLAB XC compiler User's Guide for more information on dynamic memory allocation.


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

  int * block = NULL;  /* assigned NULL so first realloc works as malloc */
  int x;
  unsigned size = 0;

  while(size != 10) {
    x = rand();
    if(x < RAND_MAX / 1000) {
      block = realloc(block, size);
      if(block == NULL)
      block[size-1] = x;
  do {
    printf("%d ", block[size-1]);
  } while(--size);

Example Output

456291 198011 524209 13456 84083 591308 86383 1887638 1277844 16807