Home > Article > Backend Development > In C language, the malloc function is used to dynamically allocate memory.
The malloc() function represents memory allocation and dynamically allocates a piece of memory.
It reserves a memory space of the specified size and returns a null pointer to the memory location.
malloc() function carries garbage values. The returned pointer is of type void.
The syntax of the malloc() function is as follows -
ptr = (castType*) malloc(size);
The following example shows the usage of the malloc() function.
Live demonstration
#include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ char *MemoryAlloc; /* memory allocated dynamically */ MemoryAlloc = malloc( 15 * sizeof(char) ); if(MemoryAlloc== NULL ){ printf("Couldn't able to allocate requested memory</p><p>"); }else{ strcpy( MemoryAlloc,"TutorialsPoint"); } printf("Dynamically allocated memory content : %s</p><p>", MemoryAlloc); free(MemoryAlloc); }
When the above program is executed, the following results will be produced -
Dynamically allocated memory content: TutorialsPoint
The above is the detailed content of In C language, the malloc function is used to dynamically allocate memory.. For more information, please follow other related articles on the PHP Chinese website!