DYNAMIC MEMORY ALLOCATION
Dynamic Memory Allocation
C language requires that the number of elements in an array should be specified at compile time. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. Many languages permit a programmer to specify an array?s size at run time. Such languages take the ability to calculate and assign, during execution, the memory space required by the variables in a program. The process of allocating memory at run time is known as dynamic memory allocation. The library functions used for allocating memory are :Function - Task
malloc( ) -Allocates requested size of bytes and returns a pointer to the first byte of the allocated space
calloc() - Allocates space for an array of element, initializes them to zero and then returns a pointer to the memory
Memory Allocation Process
Let us first look at the memory allocation process associated with a C program. Fig. below shows the conceptual view of storage of a C program in memory.- Local Variable Stack
- Free Memory Heap
- Global Variables
- C Program instructions
Allocating a block of memory
A block of 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.Example :
X = ( int * ) malloc ( 100 * size of ( int )) ;
On successful execution of this statement, a memory space equivalent to "100 times the size of an int" bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer X of type int.Similarly, the statement
Cptr = ( char * ) malloc ( 10 ) ;
allocates 10 bytes of space for the pointer cptr of type char. This is illustrated below :Cptr Address of first byte
10 bytes of Space
Remember, the malloc allocates a block of adjacent bytes. The allocation can fail if the space in the heap is not sufficient to satisfy the request. If it fails, it returns a NULL. We should therefore check whether the allocation is successful before using the memory pointer.
0 comments:
Post a Comment