Skip to main content

Malloc() Function

We are daily using pointers for dynamic memory allocation. When we declare a pointer and allocates memory for a pointer we used malloc() function. Malloc() function is a c library function. In glibc we have malloc named directory. we can see malloc's definition or its working in file named malloc.c. Malloc() returns a void pointer. And we have to typecasting as pointer declaration which type of pointer we have taken like (int* ptr,char* ptr etc.) 
Example:
 int* ptr;	
ptr = (int*)malloc(sizeof(int)*5)

Here ptr is pointer to an integer which will allocate 5 bytes for an integer. here (int*) used for typecasting. Because malloc always returns (VOID*) #include
#include
int main()
{
int* ptr;
ptr = (int*)malloc(sizeof(int));
if(!ptr)
{
perror("malloc");
exit(EXIT_FAILURE);
}
return 0;
}
If malloc successfully allocates memory it will return a void pointer otherwise it will return NULL (memory not allocated) .

Comments