Skip to content

Latest commit

 

History

History

chapter11

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Chapter 10 -- Dynamic Memory allocation

C is a language with some fixed rules of programming.
For example------ Changing the size of 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 functions available in C to allocate and free memory during runtime.

Functions 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 bytese to be allocated as an input and returns a pointer of type void.

Syntax:-
ptr = (int*)malloc(30*sizeof(int))
(int*)Casting void pointer to int
30*space for 30 ints
sizeof(int)returns size of 1 int
The expression returns a null pointer if the memory can't be allocated.

calloc() function

calloc stands for contiguous allocation.
It initializes each memory block with a default value of 0.

SYNTAX:-
ptr = (float*)calloc(30,sizeof(float);)
This allocates contiguous space in memory for 30 blocks(floats).

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

free() function

We can use free() function to de allocate the memory.
The memory allocated using calloc/malloc is not deallocated automatically.

SYNTAX:-
free(ptr); // memory of ptr is released.

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));
ptr now points to this new block of memory capable of storing 3 integers.

Exercises

  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 is can now store 10 integers.
  5. Create an array of multiplication table of 7 upto 10(7x10 = 70).Use realloc to make it store 15 numbers.
  6. Attempt problem 4 using calloc().