Memory Sizes

I am wondering why I miscalculate the memory used.......

Here is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector< void* > p;

	cout << ( sizeof( void* ) + sizeof( new int ) ) * 1000000;

	for( int i = 0; i < 1000000; i++ ){
	    p.push_back( new int( i ) );
	}
	cin.get();

	return 0;
}


why does it takes about 19MB in my task manager
it's somehow odd

since I use 1 void pointer and 1 int which is 8 byte per data
there is 1000000 data so it's should be roughly 8000000 byte == 8 MB

so 19 MB is odd
since 19MB is not even double the amount of 8MB
I think that the problem is that the vector reallocates memory many times. Try to test the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
int main() {
	vector< void* > p;
	p.reserve( 1000000 );

	cout << ( sizeof( void* ) + sizeof( new int ) ) * 1000000;

	for( int i = 0; i < 1000000; i++ ){
	    p.push_back( new int( i ) );
	}
	cin.get();

	return 0;
}


Take into account that expression sizeof( new int ) does not allocate any memory.
Last edited on
No I don't think that's the problem
it still shows ~19 MB

I think the pointer is where the problem lies

well this
 
cout << ( sizeof( void* ) + sizeof( new int ) ) * 1000000;

it's just for calculating the rough estimation

I am sure that the program won't have the perfect 8MB of memory

It will somehow get loose and missed to maybe 9MB of memory because where new int allocate memory in every loop doesn't always fit in some places.

What I don't get is why 19MB ?
As long as it doesn't leak I don't really care

but this behavior needs some explantion...
Yes I do really think it's the new int not the vector

I change the code to

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector< void* > p;
	vector< int > d;
	p.reserve( 1000000 );
	
	cout << ( sizeof( void* ) + sizeof( new int ) ) * 1000000;

	cin.get(); //pts 1

	for( int i = 0; i < 1000000; i++ ){
	    p.push_back( new int( i ) );
	}
	
	cin.get(); //pts 2
	
	for( int i = 0; i < 1000000; ++i ){
		delete (int *) (p[i]);
	}

	cout << endl;
	cin.get(); //pts 3

	return 0;

}


at point 1 about 204 KB memory is used ( usual stuff for console applocation )
at points 2 it's about 19MB
at point 3 it's about 4MB

So now I do really think it's the new int

Can some explain this strange behavior here ?
There is probably some overhead with the dynamic allocation. It looks like each int you allocate with new takes up 16 bytes instead of 4.
Topic archived. No new replies allowed.