Dynamic Memory Allocation

This is the means by which a program can obtain and release memory at run-time. This is very important in the case of programs which use large data items e.g. databases which may need to allocate variable amounts of memory or which might have finished with a particular data block and want to release the memory used to store it for other uses.

The functions malloc() and free() form the core of C's dynamic memory allocation and are prototyped in <malloc.h>. malloc() allocates memory from the heap i.e. unused memory while available and free() releases memory back to the heap.

The following is the prototype for the malloc() function
void * malloc( size_t num_bytes ) ;
malloc() allocates num_bytes bytes of storage and returns a pointer to type void to the block of memory if successful, which can be cast to whatever type is required. If malloc() is unable to allocate the requested amount of memory it returns a NULL pointer.

example to allocate memory for 100 characters we might do the following
#include <malloc.h>
void main()
{
char *p ;
if ( !( p = malloc( sizeof( char ) * 100 ) )
{
puts( "Out of memory" ) ;
exit(1) ;
}
}

The return type void * is automatically cast to the type of the lvalue type but to make it more explicit we would do the following
if ( !( (char * )p = malloc( sizeof( char ) * 100 ) )
{
puts( "Out of memory" ) ;
exit(1) ;
}
To free the block of memory allocated we do the following
free ( p ) ;
Note :- There are a number of memory allocation functions included in the standard library including calloc( ), _fmalloc( ) etc. Care must be taken to ensure that memory allocated with a particular allocation function is released with its appropriate deallocation function, e.g. memory allocated with malloc() is freed only with free() .
Dynamic Memory Allocation Dynamic Memory Allocation Reviewed by Unknown on 04:41 Rating: 5

No comments:

Powered by Blogger.