#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
	for(int i=0;i<10;i++)
	{
		char *a=new char[10];
		printf("%u\n",a);
	}
	return 0;
}

This is the output that i got

5377864
5377888
5377912
5377936
5377960
5377984
5378008
5378032
5378056
5378080


why the memory is increased in size of 24?

Recommended Answers

All 3 Replies

It is compiler dependent, and you should not need to worry about it.
In fact, my output is :

3740816
3740872
3740928
3740984
3741040
3741096
3741152
3741208
3741264
3741320

new can allocate memory anywhere on the heap, there is nothing that says that two consecutive calls to new allocate two blocks of contiguous memory.
The compiler will take things like memory alignment(and more) into consideration when it 'decides' where to allocate.

Is there a special reason you want to know, or just curiosity.

Along with the memory requested (10 bytes in your example), there is also other allocation overhead such as so that the number of elements is recorded, so when you do this:

delete [] a;

The system knows how many elements to free. This is especially important when you allocate an array of class objects that need to have their destructors called when you destroy the array.

Along with the memory requested (10 bytes in your example), there is also other allocation overhead such as so that the number of elements is recorded, so when you do this:

delete [] a;

The system knows how many elements to free. This is especially important when you allocate an array of class objects that need to have their destructors called when you destroy the array.

All that aside, memory allocation and management is a doctoral thesis subject. Been there, done that. I spent a couple of years researching reference counting memory management routines for C and C++ back about 10-15 years ago. I wrote a reference-counting (time-deterministic) garbage collector for C++ that is in use today to manage major manufacturing systems.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.