C Reference function malloc()

The function malloc() will allocate a block of memory that is size bytes large. If the requested memory can be allocated a pointer is returned to the beginning of the memory block.

Note: the content of the received block of memory is not initialized.

Usage of malloc():


void * malloc ( size_t size );

Parameters:

Size of the memory block in bytes.

Return value:

If the request is successful then a pointer to the memory block is returned.
If the function failed to allocate the requested block of memory, a null pointer is returned.

Source code example of malloc():


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

	int main ()
	{
		int * buffer;

		buffer = (int*) malloc (10*sizeof(int));
		if (buffer==NULL)
		{
			printf("Error allocating memory!");
			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: