Use realloc function to allocate memory or free memory

Syntax

C realloc function has the following syntax.

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

C realloc function is from header file stdlib.h.

Description

C realloc function reallocates memory.

If ptr is null, realloc() simply allocates size bytes of memory and returns a pointer. If size is zero, the memory pointed to by ptr is freed.

Example

Use C realloc function to allocate memory or free memory.


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{//from w ww .  ja v  a  2s. c  om
  char *p;

  p = malloc(17);
  if(!p) {
    printf("Allocation Error\n");
    exit(1);
  }

  strcpy(p, "This is 16 chars");

  p = realloc(p, 18);
  if(!p) {
    printf("Allocation Error\n");
    exit(1);
  }

  strcat(p, ".");

  printf(p);

  free(p);

  return 0;
}

The code above generates the following result.





















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h