Saturday, May 02, 2009

Dynamic Memory Allocation

Allocation of memory during execution is called dynamic memory allocation. C provides library functions to allocate and free memory dynamically during program execution. Dynamic memory is allocated on the heap by the system.


#include "stdlib.h"
int *ptr;
ptr = (int *)malloc(sizeof(int));






Now, if the pointer returned by malloc() is not NULL, we can make use of it to access the memory indirectly. For example:
if (ptr != NULL)
*ptr = 23;

Or, simply,
if (ptr)
*ptr = 23;
printf("Value stored is %d\n", *ptr);


Deallocate
free((void *) ptr);

or simply,
free(ptr);

It is possible to allocate a block of memory for several elements of the same type by giving the appropriate value as an argument. Suppose, we wish to allocate memory for 100 float numbers. Then, if fptr is a float *, the following statement does the job:

fptr = (float *) malloc(100 * sizeof(float));

No comments:

Post a Comment