# A brief note on how malloc() works in C

``` malloc() ``` is a C Standard Library function that is defined in ``` stdlib.h ``` header file.

The name malloc stands for **Memory Allocation**. 

## Definition :
``` malloc() ``` is a function that is used to dynamically allocate a block of memory with the specified size at run time. It returns a pointer of type void which can then be typecasted into any type of pointer. 

## Syntax of malloc() :

```c
void * malloc(int);
``` 
Here: 

- ``` int ``` refers to an integer value of the memory size to be created dynamically. 

- ``` void * ``` will return the pointer to the 1st byte of the memory block that was created.

### Example : 

```c
int *p = (int *) malloc(2);
``` 

To Create a platform-independent code, it's always recommended to use the ``` sizeof() ``` operator. 

```c
int *p = (int *) malloc(sizeof(int));
```

That's all about the basic definition and syntax. Now let's understand how malloc() works internally. 

## In Depth :

Since ``` malloc() ``` is a library function, it will run in the user mode, and we all know that in user mode, we do not get the powers to modify the system as much. 

So ``` malloc() ``` has to call the system call to be able to get the uninitialized memory. 

In UNIX, ``` sbrk(n) ``` is a system call that helps in creating dynamic memory allocation. 

``` malloc() ``` will call the system call internally (in unix its ``` sbrk() ```) to get the memory block which is greater in size than requested. Later if the user needs more memory then ``` malloc() ``` will give from the extra chunk that it got.

``` malloc() ``` maintains all the locations of the memory block that Operating System provides to it. 

**Point to Remember:** Operating System will not always allocate a continuous memory block to malloc for every request. 

So to manage these memory blocks, malloc makes use of the Linked List data structure. 
``` malloc() ``` will create a Linked List to store all the memory blocks and their addresses. 

``` malloc() ``` uses the first fit technique to store the data in those memory blocks because it is very efficient than the best fit technique. 


## Program Example :

```c
// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, i, *ptr, sum = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    ptr = (int*) malloc(n * sizeof(int));
 
    // if memory cannot be allocated
    if(ptr == NULL)                     
    {
        printf("Error! memory not allocated.");
        exit(0);
    }

    printf("Enter elements: ");
    for(i = 0; i < n; ++i)
    {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }

    printf("Sum = %d", sum);
  
    // deallocating the memory
    free(ptr);

    return 0;
}
```




