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() 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.
For example : to allocate memory for 100 characters we might do the following
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() .