Dynamic Memory Allocation in C using malloc( ),calloc( ),free( )
Dynamic Memory Allocation :
Malloc ( ) : The function most commonly used for dynamic memory allocation
is malloc ( ). The prototype of the function is given below –
void * malloc (size_+size)
Malloc ( ) returns a
pointer to space for an object of size, or null if the request cannot be
satisfied.
The syntax is the
function is given below –
x = (int*)malloc(hundred *
size of (int));
On successful execution
of this statement, a memory space equivalent to ‘hundred times the size of an
int’ bytes is reserved and the address of first byte of the memory allocated is
assigned to the pointer x of type of int.
Calloc ( ) : Calloc ( ) is another memory
allocation function that is normally used for requesting memory space at run
time for storing derived data types such as arrays and structures. While malloc
allocates a single blog of storage place, calloc allocates multiple blocks of
storages, each of the same size and then sets all bytes to zero.
General
Form :
ptr =
(cast_type *)calloc(n = elen_size);
The above
statement allocates contiguous space for n blocks, each of size elen_size
bytes. All bytes are initialize to zero
and a pointer to the first byte of the allocated resin is returned. If there is
not enough space, a null pointer is return.
Free ( ) : Compile time storage of a variable is allocated and released
by the system in accordance with its storage class with the run time
allocation, it is our responsibility to relies the space , when it is not
required. The relies of storage space becomes important when the storage is
limited.
When we no longer need the data we store in a block of memory and we do
not intend to use that block for storing any other information, we may relies
that block of memory for future use, using the free ( ) function.
Example
:
free (ptr);
Where ptr is
the pointer to a block of memory, which has been allocated from the heap on
request. This function is void in nature and does not returned anything.
Re – alloc (
): When the previously allocated memory
is not sapient and we need additional space for more elements. It is also
possible that the memory allocated is much larger then necessary and we want to
reduce it. In both the cases we can change the memory size already allocated
with the help of function re – alloc.
This process is called re – allocation of memory.
Example
:
ptr = malloc
(size);
ptr = realloc
(ptr,new size);
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment