malloc ( ) function
The malloc ( ) functions
allocates a block of memory of specified size from the memory heap. The
declaration of malloc ( ) is of the
form
void *malloc ( size_t size);
Here size is the
number of bytes of storage to be allocated. The size_t corresponds to the data types of the size. The malloc ( ) function returns a void
pointer to the newly allocated block of memory. Its type is automatically
converted to the type of the pointer on the left side of assignment operator.
It it fails to allocate piece of memory, it returns a null pointer. Normally
this happens where there is not enough memory.
Suppose x is a pointer to int type. Then it can be allocated memory to store 10 elements using
the following statement.
int *x;
where,
In above example, malloc is a function which reserves
memory equal to that much as given in parentheses and return the starting
address of that memory to a pointer type variable x.
Here 10*sizeof (int) means a total of 20 bytes is allocated and address is
stored in x variable.
The (int) written before the malloc function tells that x is pointing to an integer variable
and the malloc function is type casted to return the address of integer
variable.
The storage space allocated
has no name, therefore the contents are accessed only through pointers. We have
continuous memory allocations in case of malloc
( ) function and if sufficient amount of space is not allocated then it
returns a NULL.
Post a Comment