14.17 – Dynamic memory allocation – Part 1

by subbu on February 1, 2014

Need of dynamic or run-time memory allocation

Actually the memory allocation of any variable, array or pointer is planned during the compilation of the program. Only relative addresses (not exact addresses) of different memory segments are set at this stage but, actual memory allocation of these objects allocate during the execution of program in the machine on which the program is being executed.

There are some limitations with compile time memory allocation

Allocated objects would be de-allocated only on completion of function execution in which objects are declared. We can’t de-allocate the objects when we don’t want them any more.

We need to specify the size of array while writing the code, out of which only a few elements may be used during the execution of program. It results wastage of memory because allocated memory can’t be expanded or compressed.

Answer to these problems is dynamic memory allocation or run-time memory allocation.

Dynamic memory allocation

Allocating and de-allocating memory during the execution of program (runtime) is called dynamic or runtime memory allocation. The functions used for dynamic memory allocation are

  • malloc()
  • realloc()
  • calloc()
  • free()

malloc()

It is a function defined within the header file “stdio.h”. It accepts the size as argument, allocates the memory of specified number of bytes in the heap segment and returns the first byte number (address) as a void pointer type.

malloc() in C language

Say for example,

void *p;
p=malloc(8);

It allocates 8 bytes of memory in the heap and the address of first byte is returned as a void pointer.

As we know the scale factor of void pointer is zero, we can’t perform address arithmetic with void pointer (address) returned by malloc() So, the allocated memory would be useless

Hence we need to typecast the void pointer into other pointer type to perform address arithmetic and to make use of allocated memory.

short *p;
p=(short*)malloc(10);

It selects 10 bytes of memory from the heap and the address of first byte is typecasted to short* and stored into short type of pointer p. Now the pointer p could access two adjacent bytes as the scale factor of short type is 2

malloc() in C language

As the scale factor of short type is 2, adding 1 to the short pointer results increase in its value by 2. Hence p+0 is 6232, p+1 would be 6234 and p+4 would be 6240

We can access every element using address arithmetic and dereferencing as

for(i=0;i<5;i++)
       *(p+i)

Let us go through another example

float *p;
p=(float*)malloc(8);

It selects 8 bytes of memory in the heap and the first byte address is returned. It is assigned to a float pointer. Now the float pointer could access adjacent 4 bytes as the scale factor of float is 4

malloc() function

As the scale factor of float is 4, p+0 is 6332 and p+1 would be 6236. *(p+0) would be 18.256320 and *(p+1) would be 234.456734.

free()

The flexibility with the dynamic memory allocation is capability of allocating and de-allocating memory whenever we need in runtime. It is the function defined within the header file “stdio.h”. It accepts the address of memory allocation allocated by malloc() and de-allocates the memory. The de-allocated memory would be used by some other source.

It helps to effectively use the memory while developing complex applications.

free() in C language

short *p;
p=(short*)malloc(8);   /* allocates 8 bytes of memory   */
free(p);                      /* de-allocates allocated memory */

Specification: Accept two integers and print the sum of them

#include<stdio.h>
int main()
{
/* declaration of pointers */
int *p,*q,*r;
/* allocating memory       */
p=(int*)malloc(sizeof(int));
q=(int*)malloc(sizeof(int));
r=(int*)malloc(sizeof(int));
printf("Enter two integers:\n");
scanf("%d%d",p,q);   /* p,q holds the addresses of allocated memory */
*r=*p+*q;
printf("Sum of two numbers %d",*r);
free(p);free(q);free(r); /* de-allocating memory */
return 0;
}

Execution:
Enter two integers:
34
56
Sum of two numbers 90

clip_image005

The size of int type is compiler dependent, hence malloc(sizeof(int)) allocates required memory to handle integer. Say for example on Turbo C compiler int takes 2 bytes, sizeof(int) gives 2 and malloc(2) allocated 2 bytes of memory, incase of gcc compiler allocates 4 bytes of memory.

p, q give the addresses of allocated memory and *p, *q and *r access the allocated memory through dereferencing.

Specification: Accept n integer elements into the program and print the sum of them

#include<stdio.h>
int main()
{
short n,i,sum,*p;
printf("How many elements?");
scanf("%d",&n);
/* allocating memory allocation of n elements */
p=(short*)malloc(sizeof(short)*n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
  scanf("%d",p+i);
for(sum=0,i=0;i<n;i++)
  sum=sum+*(p+i);
printf("Sum of all the elements %d",sum);
free(p);
return 0;
}

Execution:
How many elements?5
Enter 5 elements:
23 44 56 34 11
Sum of all the elements 168

dynamic array

the advantage with dynamic memory allocation is demonstrated with this example. Allocated only the required number of bytes using malloc(sizeof(short)*n) where if n  is 5 then allocates 2*5 that is 10 bytes of memory.

By using address arithmetic, we could access two adjacent bytes every time the pointer is incremented. So, it can be thought as a dynamic array. We can access every element of dynamic array even by using subscript as

for(sum=0,i=1;i<n;i++)
sum=sum+p[i];

Specification: Accept n integers and print the minimum and maximum elements of accepted set

#include<stdio.h>
int main()
{
int n,i,min,max,*p;
printf("How many elements?");
scanf("%d",&n);
p=(int*)malloc(sizeof(int)*n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
  scanf("%d",&p[i]);
for(min=max=p[0],i=1;i<n;i++)
{
 if(p[i]<min)
   min=p[i];
 if(p[i]>max)
   max=p[i];
}
printf("Minimum element %d",min);
printf("\nMaximum element %d\n",max);
free(p);
return 0;
}

Execution:
How many elements?5
Enter 5 elements:
45 11 55 60 10
Minimum element 10
Maximum element 60

Previous post:

Next post: