Dynamic allocation C

When we say int X[10], the compiler assigns 10 * 2 = 20 bytes of memory to X. Using pointers, dynamic allocation of memory can be done. Dynamic allocation is allocating memory dynamically i.e. at execution time.
If we say

int *X;

X is not assigned a memory block when it is defined as a pointer, sufficient amount of memory can be assigned to X by using the memory allocation malloc().

X = malloc(10 * sizeof (int));

The above statement assigns a block of memory to X whose size is equal to 10 * size of integer quantity. The malloc() returns a pointer to character. But since X is a pointer to int, to maintain the consistency we use typecasting.

X = (int*) malloc(10 * sizeof (int));

This is known as dynamic allocation. In dynamic allocation, memory can be allocated and freed as and when required. Hence there is no wastage of space. The only limit being the available space for allocating memory.

Another function calloc can be used instead of malloc(), which initializes to 0, the memory block allocated. While in case of malloc they contain garbage values.

It can be used to append memory to existing memory block. If we have assigned 10 bytes to X using malloc(). And later we decide to add 4 bytes to X, again using malloc(), it will assign 4 bytes but previous 10 bytes will be lost. Thus using realloc() adds 4 bytes to existing 10 bytes.

It frees the specified memory block to be used for other purpose.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics