Dynamic Memmory Allocation
The malloc() function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.The storage is not initialized.
int *ptr = malloc(sizeof(int) * 10); // allocates 10 ints!
If it is unable to find the requested amount of memory, malloc() function returns NULL. So you should really check the result for errors:
int *ptr = malloc(sizeof(int) * 5000);
if (ptr == NULL)
printf(” Out of memory!\n”);
There are only two ways to get allocated memory back. They are exit from the program and calling free() to free function. If your program runs a while and keeps malloc()ing and never free()ing when it should, it is said to “leak” memory. Make sure to avoid memory leaks! free() that memory when you are done with it!
The following example illustrates the use of malloc() function.