How to allocate memory in C explain with example
Explain Memory allocation process in c
Local variables
|
Free memory
|
Global variables
|
C program instructions
|
The program instructions and global and static variables are stored in region known as permanent storage area and the local variables are stored in another area called stack.
The memory space that is allocated between these two regions is available for allocation during execution of the program. This free memory region is called the heap.
The size of the heap keeps changing when program is executed due to creation and death of variables that are local to functions and blocks. Therefore it is possible to encounter memory overflow during dynamic allocation process. In such situations the memory allocation function return a NULL pointer.
A block of memory may be allocated using the function malloc.
The malloc function reserves a block of memory of specified size and returns a pointer of type void.
This means that we can assign it to any type of pointer.
It takes the general form :
ptr = (cast-type *) malloc (byte-size);
ptr is a pointer of type cast-type. The malloc returns a pointer
(of cast-type) to an area of memory with the size byte-size.
For example :
x = ( int * ) malloc ( 100 * sizeof(int) );
On successful execution of this statement, a memory space equivalent to 100 times the size of an int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x. of type of int.