malloc( ) function in C

This “malloc( ) function in C” post is providing clear information about malloc( ) function of stdlib.h header file and how to allocate memory to structures in C programming.


 

Dynamic memory allocation to structures :

  • Generally structures are used to store more than one element of different types.
  • for example students records, emp details and so on…
  • We use static structures(fixed size) only if we know how many records to store.
  • If we don’t know how many employee records/ student records we need to store, we use dynamic memory allocation.
  • In DMA, memory will be allocated while application is running.

 

malloc( ):

  • Available in stdlib.h header file.
  • Used to allocate the memory to structures.

 

prototype :
  • void* malloc(size_t size);

 

  • “size_t” represents “unsigned” data type. We need to pass only +ve integer value.
  • malloc function allocates the memory dynamically. It allocate specified “size” bytes and returns base address of memory block in the form of void*.

 

Question : why return type is void* ?
Answer : As a programmer, we can allocate the memory using malloc( ) function to different types of structure definitions.

  1. Employee
  2. Student
  3. Single linked list node
  4. Double linked list node

 

void* pointer is called “Generic pointer”, that can capable of storing any kind of pointer.

int* —> can stores only integer data address
float* —> can stores only float data address
structure* –> can stores only structure data address
void* —> can stores any kind of data address.

  • It is recommended to type cast void* to a specific type of pointer.
  • The following diagram explains clearly how to type cast after allocating memory to structure using malloc()

malloc function in C



 

Share this