In c language there are 3 terms that are used for dynamic
memory allocation. If we allocate the data through dynamically, then that would
be available until the program terminates (like global variables).
we
can have choice when to allocate and de-allocate. De-allocation can be done
using free() function.
1) Malloc() :
The name malloc stands for "memory
allocation". The function malloc() reserves a block of
memory of specified size and return a pointer of type void which
can be casted into pointer of any form.
void *p = malloc(sizeof (int))
- As it a void pointer, we can’t directly dereference it .
like *p = 2; // gives an error.
- Before using, we have to typecast to the system defined data types ( int, float, char etc ).
int
*q = (int* )p ;
*p
= 10; // no error
- After allocating the memory, if we won’t initialize the values, then garbage values will be present.
Calloc() :
Calloc()
also allocates the blocks of memory and also initializes the allocated memory
to value equal to 0 ( like in malloc() garbage values will be present). It also
takes 2 function arguments as inputs.
1)
Number of blocks.
2)
Size of each block.
int *p = (int*) calloc(n, sizeof(int))
Example:
int *p =
(int*) calloc(25, sizeof(int))
This statement allocates contiguous memory
space for an array of 25 elements each of size of int, i.e. 4 bytes.
- calloc can be defined using malloc function as follows :
char *p = (char*) (10* malloc( sizeof(int)));
memset(p, ’0’ , 10);
The
10 memory address locations will have value 0.
Realloc() :
realloc()
is used to reallocate the memory for the given pointer either to increase the
memory block or decrease the memory block.
Syntax :
int *b = (int*) realloc( oldblock, new
memorysize);
- It first looks whether the old block can be extended if we want more memory. If it is not possible, then a new block of memory is allocated and the old values are copied.
- After copying the old block of memory into the new memory location, old one is automatically deleted.
- If we reduce the size of memory block, then remaining memory is de-allocated automatically.
- free() statement can also be done using realloc().
int *b = (int*)
realloc(b, 0);
- malloc() function can be done using realloc().
int *b = (int*)
realloc(NULL , n*sizeof(int) );
SEE ALSO :