C programming

Chapter 11

Dynamic Memory Allocation

Memory allocation in C programming

C is a language with some fixed rules of programming for example changing the size of an array is not allowed in C Programming

Dynamic Memory Allocation

Dynamic memory allocation is a way to allocate memory to a data structure during the runtime we can use a Dynamic Memory Allocation functions available in C to allocate and free memory during runtime

Functions for dynamic Memory Allocation in C programming

Following functions are available in C to perform Dynamic Memory Allocation

  1. malloc()
  2. calloc()
  3. free()
  4. realloc()

malloc () function

malloc stands for memory allocation it takes number of bytes to be allocated as an Input and returns a pointer of type void

Syntax :
ptr=(int*) malloc(40, sizeof(int));

The expression returns a null pointer if the memory cannot be allocated

Calloc() function

CallocStands for continuous allocation it initialises each memory Block with the default value of 0

Syntax 
ptr = (float*) calloc (40,sizeof(float));

If space is not sufficient then memory allocation failed and a null pointer is returned

Free() function

We can use free() function to be allocate the the memory.

The memory allocated using calloc malloc is not deallocated automatically.

Syntax 
free(ptr);

realloc ( ) function

Sometimes the dynamically allocated memory is insufficient or more than required.

realloc is used to allocate memory of new size using the previous pointer and size

Syntax 
ptr = realloc (ptr, newsize);
ptr = realloc (ptr, 3* sizeof(int));
@hytek21