Pointer Dynamic Memory Allocation In C Language

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

Syntax
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

CODE/PROGRAM/EXAMPLE
#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

CODE/PROGRAM/EXAMPLE
if (  !( (char * )p = malloc( sizeof( char  ) * 100  ) )
{
  puts( "Out of memory" ) ;
  exit(1) ;
}

To free the block of memory allocated we do the following

Syntax
free ( p );
Notepad

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_in_c #dynamic_memory_allocation_in_c_language #malloc_c #malloc_and_calloc #realloc_c #memory_allocation_in_c #calloc_c #malloc_and_calloc_in_c

(New page will open, for Comment)

Not yet commented...