C Reference function realloc()

The function realloc() reallocates a memory block with a specific new size. If you call realloc() the size of the memory block pointed to by the pointer is changed to the given size in bytes. This way you are able to expand and reduce the amount of memory you want to use (if available of course.)

It is possible that the function moves the memory block to a new location, in which way the function will return this new location. If the size of the requested block is larger then the previous block then the value of the new portion is indeterminate.

If the pointer is NULL then the function will behave exactly like the function malloc(). It will assign a new block of a size in bytes and will return a pointer to it.

If the size is 0 then the memory that was previously allocated is freed as if a call of the function free() was given. It will return a NULL pointer in that case.

Usage of realloc():

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

Parameters:

A pointer (ptr) to a previously allocated block of memory.
(The memory was previously allocated with malloc(), calloc() or realloc() functions.)

A new size in bytes for the new memory block.

Return value:

Will return a pointer to the reallocated memory block. If the function fails then a NULL pointer is returned.

Source code example of realloc():


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

	int main ()
	{
		int * buffer;

		/*get a initial memory block*/
		buffer = (int*) malloc (10*sizeof(int));
		if (buffer==NULL)
		{
			printf("Error allocating memory!");
			exit (1);
		}

		/*get more memory with realloc*/
		buffer = (int*) realloc (buffer, 20*sizeof(int));
		if (buffer==NULL)
		{
			printf("Error reallocating memory!");
			//Free the initial memory block.
			free (buffer);
			exit (1);
		}
		free (buffer);
		return 0;
	}

This entry was posted in C Reference stdlib.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

Leave a Reply: