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. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 5 responses to “C Reference function malloc()”

Why not let us know what you think by adding your own comment!

  1. Sonagara on June 8th, 2012:

    int x=5;
    printf(“%d”,x>>1);
    hows it work o/p is 2

  2. adithya on July 7th, 2012:

    writing x>>1 is equivalent in writing x divided by 2 power 1. ie., the use of >> is used to indicate the division by the powers of 2, in the same way << is used to indicate the multiplication by the power of 2

  3. som on October 30th, 2012:

    how to create user defined malloc function?, what i mean is how can a user will be able to allocate a specific amount of memory.

  4. sarika keshri on March 9th, 2013:

    very good answer…

  5. andre on July 29th, 2013:

    Maybe you could use a argv[] so user can enter the size of the memory block as a parameter, and the just use

    size = atoi(argv[]);
    malloc((size_t) size);

    something like that, if I got your question right.