C Dynamic Memory Allocation

Memory allocations process

According to the conceptual view the program instructions and global and static variable in a permanent storage area and local area variables are stored in stacks.
The memory space that is located between these two regions in available for dynamic allocation during the execution of the program. The free memory region is called the heap.
The size of heap keeps changing when program is executed due to creation and death of variables that are local for functions and blocks. Therefore it is possible to encounter memory overflow during dynamic allocation process.

Allocating a block of memory

Example: 
		x=(int*)malloc(100*sizeof(int)); 
On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int

Allocating a block of memory

A block mf 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 following 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 size byte-size.

Allocating multiple blocks of memory

Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:
ptr=(cast-type*) calloc(n,elem-size); 

The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned.
If there is not enough space a null pointer is returned.

Make Comments..!!


Oops!! No posts from user.

Download Android App