Dynamic Memory Allocation in C++


All the functions of Dynamic memory allocation like malloc, calloc, realloc, free etc. are defined in a header <cstdlib>. These functions are used to allocate and deallocate dynamic memory. Two operators named new and delete are used for allocating and freeing the memory respectively in a better and easier way.

Dynamic memory is allocated using ‘new’ operator. The memory which is dynamically allocated using new operator can be freed using ‘delete’ operator. Syntax of new and delete operator is -

1. ptr_var = new data_type; 3. delete ptr_var;

2. ptr_var = new data_type[size]; 4. delete[] ptr_var;


Let’s see the use of other memory allocation functions in programming:

I. malloc() function: In simple words, malloc means memory allocation. This function allocates memory blocks of given size and returns a pointer to the beginning of the block. The syntax of malloc() function is -

data_type *ptr = (data_type*)malloc(byte_size)

II. calloc() function: calloc stands for contiguous allocation. It allocates multiple blocks of memory and returns a pointer to the first block. Normally it takes two arguments one is number of blocks to be allocated and other is size of each block.

Syntax of calloc() function is -

data_type *ptr = (data_type*)calloc(no. of blocks, size of block);

III. realloc() function: realloc stands for reallocation. Basically, it is useful to modify the size of allocated memory which is previously allocated with the help of malloc or calloc function. The syntax of realloc function is -

realloc(ptr_variable, byte_size)

IV. free() function: It is uesd to dynamically deallocate the memory. Whenever dynamic allocation takes place free() function is used to reduce the wastage of memory. The syntax of free() method is given by -

free(ptr)


Below are few screenshots of the code for our system in which we have used these dynamic memory allocation concepts:


Use of malloc(), new and free() functions

- Aman Ladkat (K 45)

References-


Comments

Post a Comment

Popular posts from this blog

Do you have a ticket?

It's moderator's Office