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.
- Available in stdlib.h header file.
- Used to allocate the memory to structures.
- 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.
- Single linked list node
- 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()
struct emp *ptr;
ptr = (struct emp*)malloc(sizeof(struct emp));
printf("out of memory\n");
printf("Enter emp details\n");
scanf("%d%s%f",&ptr->eno, ptr->ename, &ptr->esal);
scanf("%d\n%s\n%f\n",ptr->eno, ptr->ename, ptr->esal);