The exact size of array is unknown until the compile time,i.e., time when a compiler compiles code written in a programming language into a executable form. The size of array you have declared initially can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a program to obtain more memory space, while running or to release space when no space is required.
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.
1. malloc()
- memory allocation
- Allocates requested size of bytes and returns a pointer first byte of allocated space
- syntax: 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.
- example: ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.
2. calloc()
- contiguous allocation
- Allocates space for an array elements, initializes to zero and then returns a pointer to memory
- syntax: ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements.
- 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.
3. free()
- dellocates the previously allocated space
- syntax: free(ptr);
This statement causes the space in memory pointer by ptr to be deallocated.
4. realloc()
- Changes the size of previously allocated space
- syntax: ptr=realloc(ptr,newsize);
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().
Here, ptr is reallocated with size of newsize.
No comments:
Post a Comment