Sunday 28 December 2014

malloc () function in C

malloc is short form of memory allocation. This function is used to allocate block of memory on heap memory. Function definition resides in stdlib.h header file.

void * malloc(size_in_bytes)

malloc function returns a void pointer which contains the address of the first byte in the allocated block of memory. Size_in_bytes is the size of block we want malloc function to allocate when it is called in the program. If we have specified the Size_in_bytes more than what is available in the heap memory then this function will return a NULL.
We need to type cast the void pointer into the data type which we need to allocate memory for.

Hence we will use this function as below in our program.

type *ptr = (type *)malloc(size_in_bytes)

Note - If we allocate memory using this function, the allocated memory block will contain garbage value. We need to initialize the pointer before using it so that we do not use the garbage value contained in. Malloc function will not initialize the memory block allocated on heap memory.

C Code Example

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

/* stdlib.h contains the definition for malloc() function. */

int main()
int *ptr;    // ptr is declared as a pointer to an integer

ptr = (int*)malloc(sizeof(int));  

/* malloc function is called with an argument which is another function sizeof().sizeof() returns the number of bytes of memory the specified data type will take. In this case sizeof(int) will return 4 which means 4 bytes which is required on my machine to store a integer variable. ptr will now have the address of first byte of the 4 bytes malloc allocated. */

if(ptr=NULL)
{
puts("malloc call failed");
}
else
{
*ptr = 7;
}
printf("Integer we stored at address ptr is = %d",*ptr);
free(ptr);

/* free() function will free the memory allocated by malloc. If we do not free the memory this block of memory will not be available for the program and may cause memory leak issue. */

getch()

}

Output of above program will be :

Integer we stored at address ptr is = 7


















 

No comments:

Post a Comment