codescracker


c

C realloc()



« Previous Function C Tutorial »


realloc()

The precise operation of realloc() differs slightly between C89 and C99, although the net effect is the same. For C89, realloc() changes the size of the previously allocated memory pointed to by ptr to that specified by size. The value of size can be greater or less than the original. A pointer to the memory block is returned because it may be necessary for realloc() to move the block in order to change its size. If this occurs, the contents of the old block (up to size bytes) are copies into the new block.

For C99, the block of memory pointed to by ptr is freed, and a new block is allocated. The new block contains the same contents as the original block (up to the length passed in size). A pointer to the new block is returned. It is permissible, however, for the new block and the old block to begin at the same address. That is, the pointer returned by realloc() might be the same as the one passed in ptr.

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

If there is not enough free memory in the heap to allocate size bytes, a null pointer is returned, and the original block is left unchanged.

realloc() Syntax

Following is the syntax of the realloc() function :

#include<stdlib.h>
void *realloc(void *ptr, size_t size);

realloc() Example

Following program first allocates 17 characters, copies the string "This is 16 chars" into them, and then uses realloc() to increase the size to 18 in order to place a period at the end.

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

void main()
{
	clrscr();
	
	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);
	
	getch();
}

« Previous Function C Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test