Tuesday, September 23, 2014

DYNAMIC MEMORY ALLOCATION PROGRAMMING

Dynamic Memory Allocation
For Dynamic memory allocation pointer concept used. Dynamic memory allocation means program to obtain memory space at runtime.
There are 4 library functions under "stdlib.h" for dynamic memory allocation.
malloc()
Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc()
Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free()
deallocate the previously allocated space
realloc()
Change the size of previously allocated space
malloc()
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()

ptr=(cast-type*)malloc(byte-size)
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.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 according to size of int 2 bytes respectively and the pointer points to the address of first byte of memory.

calloc()

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()

ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

free()

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()

free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.


No comments:

Post a Comment

12th January Swami Vivekanand Jayanti: National Youth Days

The day serves as a reminder to the youth of India to remain steadfast in their goals and contribute positively to society. Swami Vivekanand...