Dynamic Allocation in C: malloc () function and free() function

Dynamic Allocation in C: There are situations when we don’t know the total memory required by a C program before execution. Dynamic allocation is a process in which a program can get memory while it’s running. A program gets its memory during dynamic allocation from the heap. A heap is a free memory area which lies between the program and the permanent storage area.

Dynamic Allocation Functions: There are two dynamic memory allocation functions: malloc () and fre (). malloc () function is used to allocate memory and free () function is used to release memory. These functions are present in the standard library stdlib.h

malloc () function:

Syntax of malloc () function:

void *malloc(size_t number_of_bytes);

A malloc ()function can be assigned to any pointer.  For Example to allocate 200 bytes of memory:

char *a;

a = malloc(200);

When there is not enough memory for a malloc () function then, malloc() function returns a null value.

free() function: A free (0 function is used to release the memory allocated by a malloc() function.

Syntax of free() function:

void free(void *a);

a is a pointer to memory which was previously allocated by malloc () function.

A free() function should never be called by an invalid argument. This destroys the free list.

Leave a Reply