Malloc () is used to allocate user-defined bytes on the heap.
#include <stdio.h> #include <stdlib.h> int main() { //Allocating memory dynamically on the heap //for an integer, which returns an int* pointer int* a = (int*) malloc (sizeof(int)); if (a != NULL) printf("Allocated memory for an integer\n"); else printf("malloc() failed"); int x = 100; //We can update the value to this location, since //we have allocated memory for the pointer *a = x; printf("a points to %d\n", *a); int* b; //Will give a segmentation fault, since //*b is not allocated any memory *b = x; printf("b points to %d\n", *b); //Free memory from the heap free(a); return 0; }Source:wwual.wtturi.com
This example uses' malloc() 'to allocate memory for the integer position pointed to by a.
Since memory has been allocated, this value can be updated.
However, another pointer b that did not allocate memory anywhere could not update its value, and a segmentation error occurred due to an attempt to access a NULL location.
output:
Allocated memory for an integer a points to 100 [1] 14671 segmentation fault (core dumped) ./a.out