Sunday, March 14, 2021

CH 11:Dynamic Memory Allocation

 C is a language with some fixed rules of programming. For example: changing the size of an array is not allowed.

Dynamic Memory Allocation:

Dynamic memory allocation is a way to allocate memory to a data structure during the runtime we can use DMA function available in C to allocate and free memory during runtime.


Function for DMA in C

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:

The expression returns a NULL pointer if the memory cannot be allocated.

Quick Quiz: Write a program to create a dynamic array of 5 floats using malloc().


calloc() function

calloc stands for continuous allocation.

It initializes each memory block with a default value of 0.

Syntax:

If the space is not sufficient, memory allocation fails and a NULL pointer is returned.

Quick Quiz: Write a program to create an array of size n using calloc() where n is an integer entered by the user.


free() function

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

The memory allocated using calloc/malloc is not deallocated automatically.

Syntax:

free(ptr);      => Memory of ptr is released

Quick Quiz: Write a program to demonstrate the usage of free() with malloc().


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:

Program For Practice:

  1. Write a program to dynamically create an array of size 6 capable of storing 6 integers.
  2. Use the array in Problem 1 to store 6 integers entered by the user.
  3. Solve problem 1 using calloc().
  4. Create an array dynamically capable of storing 5 integers. Now use realloc so that it can now store 10 integers.
  5. Create an array of the multiplication table of 7 upto 10 (7x10=70). Use realloc to make it store 15 numbers(from 7x1 to 7x15).
  6. Attempt problem 4 using calloc().

No comments:

Post a Comment

Decision Making in C / C++

Decision Making in C / C++ (if , if..else, Nested if, if-else-if )   There come situations in real life when we need to make some decisions ...