Skip to main content

Posts

Showing posts with the label memory management in C

What is Dynamic Memory Allocation in C

Under stdlib header C provides us 4 four special function which helps in allocating memory dynamically and freeing it. malloc() calloc() realloc() free() The first three function's are used in allocation of memory while the last one frees the allocated memory. The Malloc function Syntax malloc ( number_of_bytes ); The malloc function  allocates contiguous memory location for the required   number_of_bytes, returns a void pointer pointing to the base address of that allocated memory. A malloc returns a void pointer,why?because malloc does not know for what we allocated the memory ( malloc does not know whether we are allocating memory for ints , floats or chars ). Usage example int   * a = ( int * )  malloc (5 *sizeof ( int )); The (int*) is done for typecasting, it converts the void pointer returned by malloc function to a integer pointer (int*) . We are then assigning the returned(and type casted) pointer to a integer point a. So a is now pointing to the base address of allocated