Search This Blog

Dynamic Memory Allocation in C - Explanation With Examples

In static memory allocation, we know how much memory (bytes) is going to be used before execution of the program. Dynamic memory allocation is essential where the amount of memory the needed by the program depends on the input of the user or any other input obtained during execution time. That is why it is called dynamic memory allocation.

Consider an example of students progress report (for the sake of simplicity). The number of students are different in different classes. There fore, we have to read the number of students from the user (data entry operator). For each student, we need an integer for register number, a few integers to store scores in subjects, a few characters to store address and so on. In this case, the total amount of memory needed depends on the number of students in a class. There fore, the amount of memory that should be allocated for the program should be decided based on the input. In such cases we use dynamic memory allocation.

C programming language allows dynamic memory allocation. Most of modern programming languages use dynamic memory allocation. Java is an example. Unlike C, there is not a concept of pointers in Java because all variables are actually pointers.

Functions for Dynamic Memory Allocation in C

The functions used for dynamic memory allocation or deallocation are malloc, realloc, calloc and free. These functions are defined in the header file stdlib.h
malloc
This function is used to allocated specified number of bytes.
realloc
Used to increase or decrease size of a block of memory. Allocation or Deallocation of bytes is performed if necessary.
calloc
Allocates specified number of bytes and also intialises all bytes to zero. This function allows to specify how many blocks of specified size should be allocated.
free
Deallocates and releases the specified block of memory.
We shall see each function with examples.

Malloc function

First, we will see the syntax of malloc function. Then it will be easier to explain. Syntax is as follows:

void * malloc(int sizeInBytes);

The above shown prototype of malloc function tells that it always return a pointer to 'void' data type. That is, the pointer can be type-casted to int pointer, char pointer or to any other data type. malloc functions takes a parameter which is the amount of memory (number of bytes) to be allocated. It is recommended to specify the size using sizeof operator. We will see a few examples of dynamic memory allocation using malloc function.

int *p=malloc(10*sizeof(char));
Allocates memory to accommodate 10 characters.
int *p=malloc(20*sizeof(int));
Allocates memory to accommodate 20 integers.
int *p=malloc(sizeof(float));
Allocates memory to accommodate a float.
int *p=malloc(10*sizeof(struct student));
Allocates memory to accommodate 10 instances of structure named student. This is how to store derived datatypes (user defined data types) like structures dynamically in c.

Realloc Function

Realloc function is used either to shrink or to expand an already allocated memory. It is called after allocation of memory using malloc or calloc function. Suppose we initially allocated memory for 10000 characters dynamically. Later, during the of execution of program, we find that only 5000 characters need to be stored. Therefore, we are not going to use the rest. To avoid memory wastage, we may deallocate the remaining 5000 character spaces trailing being the used 5000. The following code will shrink the initially allocated 10000 chars to 5000 chars by deallocating the remaining.

void * realloc(void *pointer,size_t size)

The first parameter pointer is the pointer to the memory block allocated earlier. The next argument size is the new (updated) size. It size is greater than the older size, additional memory will be allocated to get size number of bytes allocated in total. If it is less than older size, a part of memory will be deallocated which is equal to the difference between initial size and new size. If first parameter is NULL, a fresh block with specified size will be allocated.

char *ptr;
//Initial allocation
ptr = (char *) malloc(150);

//Reallocating memory to 50 char
ptr = (char *) realloc(ptr, 50);

Calloc Function

Calloc function is not much significantly different from malloc. The differences between malloc and calloc are:

  • Calloc lets you to specify the number of variables (of same data type) and space needed by each data type by taking two parameters.
  • When allocated using malloc, the memory block may contain junk data (garbage values) but calloc initializes every allocated byte to zero.
The following code fragment shows example use of calloc with structure:

#include<stdlib.h>
struct student
{
int rollno;
char name[30];
};

int main()
{
struct student *list,*temp;
list=(struct student *)calloc(5,sizeof(struct student));
for(temp=list;temp-list<5;temp++)
    {
    printf("Enter roll number and name of student\n");
    scanf("%d%s",&temp->rollno,&temp->name);
    }
printf("\nThe students are:\n");
for(temp=list;temp-list<5;temp++)
    {
    printf("Roll number: %d  Name: %s\n",temp->rollno,temp->name);
    }
free(list);
return 0;
}
Output
Enter roll number and name of student
1
matthew
Enter roll number and name of student
2
mathews
Enter roll number and name of student
3
shareef
Enter roll number and name of student
4
muneer
Enter roll number and name of student
5
nihal

The students are:
Roll number: 1  Name: matthew
Roll number: 2  Name: mathews
Roll number: 3  Name: shareef
Roll number: 4  Name: muneer
Roll number: 5  Name: nihal

In the above example a structure named student is used. Each structure variable has a roll number and name. Memory to store for 5 student structure variables are allocated using calloc. The pointer arithmetic for pointers to structures is also demonstrated in above program.

Free Function

The free function is used to free (deallocate) an already allocated block of memory. When your program no longer needs the dynamically allocated block of memory, the free function should be called to return the memory occupied to the free store. In the above example program, the following line of code deallocated the allocated block of memory.

free(list);

The free function takes the pointer to the block of memory which is allocated dynamically as parameter and frees or deallocates the block so that it can be used later.

Making of Tetris Game in C

tetris block block game c program
Block types in tetris
Have you ever tried to make tetris game in c. Tetris is a simple game with minimal graphics. It is much easy to program in c. If you are not familiar with graphics.h header file, you may think it almost impossible. But, graphics.h is just a simple library justs as string.h. It is very simple to learn. Let us first see how to represent tetris as data structure. There are mainly 5 types of blocks in tetris. They are L blocks, Z blocks, I blocks, S blocks and T blocks. The blocks are shown in the picture.


To make the tetris game, we first make a two dimensional array. An element in this integer array is a single block (one of the four blocks in each block type) in the game. We set all the elements to zero initially to show that the matrix is empty. We may call each element a cell. So to represent a Z block, we need four cells. In the matrix, to represent a falling block (eg: a Z block) we set corresponding elements' values to 1. We move these 1's in the 2d integer array downwards to simulate falling. Then when it reaches bottom, these 1's are changed to 2's. This is to denote that these cell cannot be moved further. Again, we start another random block from the top (first row).

Bresenham's Line Drawing Algorithm Implementation in C - Generalized Algorithm

Bresenham's line drawing algorithm is an efficient algorithm to draw any line. Unlike DDA algorithm, it uses only integer incremental calculations during the process. This saves much of the CPU time. I am posting a generalized Bresenham's line drawing algorithm (an algorithm that can draw any line in any quadrant with any slope). The main function in this program draws lines of almost all slopes by drawing radial lines for a circle. The entered endpoints of the line are marked in red color. The rest of the line is drawn in the default stroke color in BGI graphics. You can change it by calling setcolor() function.

Output:


Program is given below:

C Program to Animate a Man Drawing Water From Well

This is a c program to animate a man drawing water from well. This is computer graphics lab experiment. The program uses graphics library in c (graphics.h). The output is as follows:


 The program is as follows:

C Program for Polygon Clipping by Another Polygon - Computer Graphics Lab Program

Polygon clipping is one of the classic problem in computer graphics lab. Generally, polygons or whatever objects, are clipped by a rectangular clipping windows. But, this one is a little more challenging graphics lab experiment in which we have to clip polygon with another polygon. That is the clipping windows is actually another polygon. The following c program implements polygon clipping with another polygon. The program clips any polygon with the clipping polygon, given both should be convex polygons.

Bresenhams Circle Drawing Algorithm Implementation in C

Bresenham's circle drawing algorithm is one of the basic algorithms in computer graphics. Bresenham's circle drawing algorithm helps to draw circles with minimal calculations. Here is a simple c program that implements Bresenham's circle drawing algorithm.

The program is as follows:

C Program to Implement Midpoint Circle Drawing Algorithm

Midpoint circle drawing algorithm is another basic algorithms in computer graphics. Midpoint circle drawing algorithm is used to draw circles with minimal calculations. Here is a simple c program that implements Midpoint circle drawing algorithm.

How to Get Time and Date in C - C Program to Read and Display Time and Date

In this post, we will discuss how to read system time (current time) and date in c. To get system time and date, we use the time.h header file. It contains functions related to time and date. The function time() reads the current time and stores in the variable given as parameter. For example, if we call time(now), then the variable now is assigned the current date and time value. This parameter should be of type time_t. A sample code is:

time_t now;
time ( &now );

Note that we should pass the reference to a variable of type time_t.  But, the value stored by the function time() contains all information including date and time. So, the value appears to be an unintelligible random number. There fore, to extract hours, minutes, seconds, year, month, day of month etc from this value, we should convert into an object of structure struct tm. The function localtime() converts the value for us. This conversion to date and time can be done as follows:

C Program to Display Analog Clock Showing Correct Time - Computer Graphics Program

This is a c program which reads the current time from system and shows an analog clock that shows correct time. The clock hand ticks and the three hands (hour hand, minute hand, second hand) are used to to show correct time. This real-time analog clock c program uses graphics.h library to display the clock and time.h library to get current time. The program output is as follows:


C Program to Draw Rainbow - Computer Graphics Pogram

This is a simple computer graphics lab program in c language to display a rainbow. Since BGI (Borland Graphics Interface) supports only 16 colors, the rainbow cannot be shown in correct colors (VIBGYOR). This is because, colors like violet, indigo and orange are not available in BGI. There fore, we just use some available color instead. The following is the program.

Rotation of Wheel - C Program for Computer Graphics Lab

In computer graphics experiments, we need to rotate objects like wheels while doing animation. This is a simple c program that shows rotation of a wheel. A circle is drawn and four radial lines are drawn at 90 degree separation. These lines are drawn from center to a point on circle which depends on the value of theta, a variable. As the value of theta changes, the end points of the radial lines changes. Therefore, increasing the value of theta in a loop give counter clockwise rotaion and decreasing gives clockwise rotation.


The program is as follows:

C Program to Draw Malayalam Letter 'Dha' (เดง) Using Bezier Curves

This is a c program to draw Malayalam letter เดง using Bezier Curves. The program draws the letter
bezier curves with control points
เดง using Bezier Curves
เดง using four different Bezier curves. For understandability, individual curves are shown in different colors. The control points for each curve are set in the program and a function bezier() is called with different set of control points twice.

C Program to Draw Malayalam Letter 'Tha' (เดค) Using Bezier Curves

This is a c program to draw malayalam letter เดค using Bezier Curves. The program draws the letter
drawing bezier curves in c program
เดค using bezier curves
เดค using four different Bezier curves. For understandability, individual curves are shown in different colors. The control points for each curve are set in the program and a function bezier() is called wth different set of control points four times.

C Program to Draw Bezier Curve - Graphics Lab Program

This is a c program to draw a bezier curve. You can draw a bezier curve by giving control points. The control points' co-ordinates are stored in arrays x[] and y[]. You can draw different curves by combining multiple bezier curves. We will see such examples in some other posts. Here, this program has a function named bezier which draws the curve using an array of control points declared globally.

C Program to Draw Fern Leaf using Fractals - Computer Graphics Experiment

Fern is a plant with leaves that follow a pattern. A whole fern plant can be drawn using simply lines. Drawing fern is a simple example for fractals in computer graphics. The following program draws a fern plant using the idea of fractals. This is a computer graphics lab experiment.

Rotation and Revolution of Two Wheels following a 'D' Shaped Path - Computer Graphics Experiment

This is a computer graphics lab experiment. The question was to animate both rotation and revolution of two wheels in opposite direction. Both the wheels move in a path in a of shape 'D'. If one moves in clockwise direction, the other moves in counter clockwise direction. The output of the program is as follows:
The program is as follows:

Keyboard Controlled Car Animation in C - Computer Graphics Lab Program

This is a computer graphics lab program. This is an animation program in which a car can be moved using the arrow keys on keyboard. The car should move forward when right arrow key is pressed and backward when left arrow key is pressed. The car accelerates as the right arrow key is pressed. When it is released the car decelerates. The program uses the graphics library graphics.h. This program works well in the turbo c compiler with Borland graphics interface (BGI). The output of the program is as follows:

The program is as follows:

Man Rowing Boat Animation - Computer Graphics Lab Animation Experiment

This is a computer graphics lab program. This is an animation program. The experiment is to animate a scene of a man rowing boat in a river on a rainy day. The man wears a hat also. The program uses the graphics library graphics.h. This program works well in the turbo c compiler with Borland graphics interface (BGI). The output of the program is as follows:

The program is as follows:

C Program for Animated Solution of Tower of Hanoi Puzzle Problem

This is a c program to solve towers of Hanoi puzzle problem with graphical demonstration. This c program demonstrates solution for tower of Hanoi puzzle with given number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of Brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. The program lets you enter the number of disks. As the number of disks increase, the difficulty of puzzle also increase. The disks have hole at center so that it can slide on to the rods. Initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. To win the puzzle you have to move all those disks from tower A (first tower) to tower C (third tower). But there are a few rules to solve the puzzle. They are:

C Program to Solve Tower of Hanoi Puzzle

This is a c program to solve towers of Hanoi puzzle problem. This simple c program give solution for tower of Hanoi problem with any number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of Brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. Initially, The disks have hole at center so that it can slide on to the rods. initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. The goal or objective is to move all these disks from tower A (first tower) to tower C (third tower). But you should obey the following rules. The rules of towers of Hanoi puzzle are: