realloc - C stdlib.h

C examples for stdlib.h:realloc

Type

function

From


<cstdlib>
<stdlib.h>

Description

Reallocate memory block

Prototype

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

Parameters

Parameter Description
ptr Pointer to a memory block previously allocated with malloc, calloc or realloc.
size New size for the memory block, in bytes.

Return Value

On success, a pointer to the reallocated memory block.

On error, null-pointer is return.

Demo Code

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

int main ()/*  w  w w.j a  v  a2s.  co  m*/
{
  int input,n;
  int count = 0;
  int* numbers = NULL;
  int* more_numbers = NULL;

  count = 1;
  more_numbers = (int*) realloc (numbers, count * sizeof(int));

  if (more_numbers == NULL) {
     free (numbers);
     puts ("Error (re)allocating memory");
     exit (1);
  }
  count = 2;
  more_numbers = (int*) realloc (numbers, count * sizeof(int));

  if (more_numbers == NULL) {
       free (numbers);
       puts ("Error (re)allocating memory");
       exit (1);
  }

  free (numbers);

  return 0;
}

Related Tutorials