Memory Allocation in C/C++

Memory Allocation in C/C++

What is memory Allocation?

There are two ways via which memories can be allocated for storing data. The two ways are:
1.       Compile time allocation or static allocation of memory: where the memory for named variables is allocated by the compiler. Exact size and storage must be known at compile time and for array declaration the size has to be constant.
2.       Run time allocation or dynamic allocation of memory: where the memory is allocated at run time and the allocation of memory space is done dynamically within the program run and the memory segment is known as heap or the free store. In this case the exact space or number of item does not have to be known by the compiler in advance. Pointers play a major role in this case.

What is Dynamic memory allocation?

Programmers can dynamically allocate storage space while the program is running, but programmers cannot create new variable names “on the fly”, and for this reason dynamic allocation requires two criteria:

•        Creating the dynamic space in memory
•        Storing its address in a pointer (so that the space can be accessed)

Memory de-allocation is also a part of this concept where the “clean-up” of space is done for variables or other data storage. It is the job of the programmer to de-allocate dynamically created space. For de-allocating dynamic memory, we use the delete operator. In other words, dynamic memory Allocation refers to performing memory management for dynamic memory allocation manually.

Static memory allocation
Dynamic memory allocation
In static memory allocation, memory is allocated while writing the C program. Actually, user requested memory will be allocated at compile time.
In dynamic memory allocation, memory is allocated while executing the program. That means at run time.
Memory size can’t be modified while execution.
Example: array
Memory size can be modified while execution.
Example: Linked list

Dynamic Memory Allocation in C

The process of allocating memory at runtime is known as dynamic memory allocation. Library routines known as "memory management functions" are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h.

Function     Description

malloc()      allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space

calloc()        allocates space for an array of elements, initialize them to zero and then returns a void pointer to the memory

free()           releases previously allocated memory

realloc()      modify the size of previously allocated space

Allocating block of Memory

malloc() function is used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to allocate enough space as specified, it returns a NULL pointer.

Syntax:
void* malloc(byte-size)

Example using malloc() :
int *x;
x = (int*)malloc(50 * sizeof(int));    //memory space allocated to variable x
free(x);                    //releases the memory allocated to variable x

calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is normally used for allocating memory to derived data types such as arrays and structures. If it fails to allocate enough space as specified, it returns a NULL pointer.

Syntax:

void *calloc(number of items, element-size)

Example using calloc() :
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));

realloc() changes memory size that is already allocated dynamically to a variable.

Syntax:

void* realloc(pointer, new-size)

Example using realloc() :
int *x;
x=(int*)malloc(50 * sizeof(int));
x=(int*)realloc(x,100); //allocated a new memory to variable x

DIFFERENCE BETWEEN MALLOC() AND CALLOC() FUNCTIONS IN C:

 

malloc()
calloc()
It allocates only single block of requested memory
It allocates multiple blocks of requested memory
int *ptr;ptr = malloc( 20 * sizeof(int) );For the above, 20*4 bytes of memory only allocated in one block. 
Total = 80 bytes
int *ptr;Ptr = calloc( 20, 20 * sizeof(int) );For the above, 20 blocks of memory will be created and each contains 20*4 bytes of memory. 
Total = 1600 bytes
malloc () doesn’t initializes the allocated memory. It contains garbage values
calloc () initializes the allocated memory to zero
type cast must be done since this function returns void pointer int *ptr;ptr = (int*)malloc(sizeof(int)*20 );
Same as malloc () function int *ptr;ptr = (int*)calloc( 20, 20 * sizeof(int) );

Program to represent Dynamic Memory Allocation(using calloc())
#include <stdio.h>
#include <stdlib.h>

int main()
{
int i, n;
int *element;

printf("Enter total number of elements: ");
scanf("%d", &n);

element = (int*) calloc(n,sizeof(int)); /*returns a void pointer(which is type-casted to int*)
pointing to the first block of the allocated space*/

if(element == NULL)//If it fails to allocate enough space as specified, it returns a NULL pointer.
    {
printf("Error.Not enough space available");
exit(0);
    }

for(i=0;i<n;i++)
scanf("%d",element+i); //storing elements from the user in the allocated space

for(i=1;i<n;i++)
    {
if(*element > *(element+i))
           *element = *(element+i);
    }

printf("Smallest element is %d",*element);

return 0;
}

Output:
Enter total number of elements: 5
4 2 1 5 3
Smallest element is 1
C++

Memory in your C++ program is divided into two parts:

  • stack: All variables declared inside any function takes up memory from the stack.
  • heap: It is unused memory of the program and can be used to dynamically allocate the memory at run time.


Allocating space with new

To allocate space dynamically, use the unary operator new, followed by the type being allocated.

Here is a code snippet showing the use of new:

new int;//dynamically allocates an integer type
new double;// dynamically allocates an double type
new int[60];

The above declared statements are not so useful as the allocated space has no names. But the lines written below are useful:

int* p; // declares a pointer p
p =new int;  // dynamically allocate an int for loading the address in p
double* d;  // declares a pointer d
d =new double;  // dynamically allocate a double and loading the address in p

The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. malloc() allocates requested size of bytes and returns a pointer to first byte of allocated space. The main benefit of new over malloc() is that new doesn’t just allocate memory, it constructs objects which is a prime concept of C++. When programmers think that the dynamically allocated variable is not required any more, they can use the delete operator to free up memory space. The syntax of using this is:

delete var_name;

Here is a simple program showing the concept of dynamic memory allocation:

Example:
#include<iostream>
int main()
{
double *val= NULL;
val=new double;
*val=38184.26;
cout<<"Value is : "<<*val<<endl;
delete val;
}

Dynamic Memory Allocation for Arrays

If you as a programmer; wants to allocate memory for an array of characters, i.e., string of 40 characters. Using that same syntax, programmers can allocate memory dynamically as shown below.

char *val  = NULL;       // Pointer initialized with NULL value
val= new char[40];     // Request memory for the variable

Dynamic Allocation Program Using Constructor

Example:
#include<iostream>

class stud {
public:
stud()
{
cout<<"Constructor Used"<<endl;
}
~stud()
{
cout<<"Destructor Used"<<endl;
}
};

int main()
{
stud* S =new stud[6];
delete[] S;

}

Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes