In this program I am trying to find out how much memory is allocated for my pointer. I can see it in this way that it should be 1 gibibyte which is = 1 073 741 824 bytes. My problem is that the only way I can get this thru is by taking the size of int which is 4 and multiplying by that const number. Is there a different way?
#include "stdafx.h"
#include <iostream>
#include <new>
int main(){
const int gib = 268435256; //Created a constant int so I could allocate 1
//Gib memory
int *ptr = new int [gib];
std::cout << sizeof (int)*gib << std::endl;
std::cout << *ptr << std::endl;
std::cout << ptr << std::endl;
try {
}catch (std::bad_alloc e) {
std::cerr << e.what() << std::endl;
}
system("PAUSE");
delete[] ptr;
return 0;
}
No, there is no way. The compiler internally adds information about how much memory was allocated and how many elements were created by new[]
, because otherwise it couldn't perform delete[]
correctly. However, there is no portable way in C++ to get that information and use it directly.
So you have to store the size separately while you still know it.
Actually, you don't, because std::vector
does it for you:
#include <iostream>
#include <vector>
#include <new>
int main() {
const int gib = 268435256;
try {
std::vector<int> v(gib);
std::cout << (v.capacity() * sizeof(int)) << '\n';
} catch (std::bad_alloc const& e) {
std::cerr << e.what() << '\n';
}
}
You should practically never use new[]
. Use std::vector
.
Note that I've used capacity
and not size
, because size
tells you how many items the vector represents, and that number can be smaller than the number of elements supported by the vector's currently allocated memory.
There is also no way to avoid the sizeof
, because the size of an int
can vary among implementations. But that's not a problem, either, because a std::vector
cannot lose its type information, so you always know how big one element is.
You wouldn't need the multiplication if it was a std::vector<char>
, a std::vector<unsigned char>
or a std::vector<signed char>
, because those three character types' sizeof
is guaranteed to be 1.