Hi friends today we are going to discuss about dynamic memory allocation, this plays a very important role in embedded development. Specially when your product is based on data entry type of application.
Dynamic allocation is a unique feature to C language. Dynamic memory allocation allows a program to obtain more memory space, while running or to release space when no space is required. It is the practice of assigning memory locations during execution of the program by explicit request of the programmer. It enables us to create data types and structures of any size and length to suit our programs need within the program.
Just think of arrays, we need to determine the size of array first hand itself, but by using dynamic allocation we eliminate the need to determine the size of array at declaration time. Dynamically allocated memory area is secured. Variables are usually allocated to the location of the stack; but for dynamic allocation heap memory area is used. When a program executes, the operating system gives it a stack and a heap to work with. The stack is where global variables, static variables, and functions and their locally defined variables reside. The heap is a free section for the program to use for allocating memory at runtime.
Although, C language inherently does not has any technique to allocated memory dynamically, there are 4 library functions under “stdlib.h” for dynamic memory allocation.
The name malloc stands for “memory allocation”. The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
This statement will allocate either 100 or 200 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.
The name calloc stands for “contiguous allocation”. The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
This statement will allocate contiguous space in memory for an array of n elements. For example:
This statement allocates contiguous space in memory for an array of 20 elements each of size of float, i.e, 4 bytes.
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().
Syntax of realloc()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space.
syntax of free()
This statement cause the space in memory pointer by ptr to be deallocated.