The C library function void *malloc(size_t size) allocates the requested memory and returns a pointer to it.
Following is the declaration for malloc() function.
void *malloc(size_t size)
size − This is the size of the memory block, in bytes.
This function returns a pointer to the allocated memory, or NULL if the request fails.
The following example shows the usage of malloc() function.
#include <stdio.h> #include <stdlib.h> int main () { char *str; /* Initial memory allocation */ str = (char *) malloc(15); strcpy(str, "tutorialspoint"); printf("String = %s, Address = %u\n", str, str); /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("String = %s, Address = %u\n", str, str); free(str); return(0); }
Let us compile and run the above program that will produce the following result −
String = tutorialspoint, Address = 355090448 String = tutorialspoint.com, Address = 355090448