Memory allocation (malloc), is an in-built function in C. This function is used to assign a specified amount of memory for an array to be created. It also returns a pointer to the space allocated in memory using this function.
In the world of programming where every space counts, there are numerous times when we only want an array to have a specific amount of space at run time. That is, we want to create an array occupying a particular amount of space, dynamically. We do this using malloc.
We know what malloc returns and we know what it requires as an input, but how does the syntax of the function work. The illustration below shows that:
Note: malloc will return
NULL
if the memory specified is not available and hence, the allocation has failed
Now that we know how malloc is used and why it is needed, let’s look at a few code examples to see how it is used in the code.
#include<stdio.h>#include <stdlib.h>int main() {int* ptr1;// We want ptr1 to store the space of 3 integersptr1 = (int*) malloc (3 * sizeof(int));if(ptr1==NULL){printf("Memory not allocated. \n");}else{printf("Memory allocated successfully. \n");// This statement shows where memory is allocatedprintf("The address of the pointer is:%u\n ", ptr1);// Here we assign values to the ptr1 createdfor(int i=0;i<3;i++){ptr1[i] = i;}// Printing the vlaues of ptr1 to show memory allocation is donefor(int i=0;i<3;i++){printf("%d\n", ptr1[i]);}}}
Line 5: We defined a pointer with the name of ptr1
.
Line 7: In the defined pointer name ptr1
we have stored the space of 3 integers.
Lines 9-11: In this section of the code, we have defined a if
condition that will print the message "Memory not allocated." if ptr1
doesn't have any assigned value.
Lines 12-14: In the else
section of the code if the ptr1
have an assigned value it will print the message "Memory allocated successfully.".
Lines 17-19: In this section of the code we have assigned values to that ptr1
that we defined in line 5.
Free Resources