feelfree
feelfree

Reputation: 11753

How can I know the allocated memory size of a std::vector?

I understand that we can use size() function to obtain the vector size, for example:

   std::vector<in> abc;
   abc.resize(3);
   abc.size();

The my question is how can I know the memory size of a vector? Take an example:

std::vector<int> abc;
abc.reserve(7);
//the size of memory that has been allocated for abc

Upvotes: 0

Views: 5358

Answers (5)

Edward Strange
Edward Strange

Reputation: 40849

The real answer is that you can't. Others have suggested ways that will often work, but you can't depend on capacity reflecting in any way the actual memory allocated.

For one thing, the heap will often allocate more memory than was requested. This has to do with optimizations against fragmenting, etc... vector has no way of knowing how much memory was actually allocated, only what it requested.

So capacity at best gives you a very rough estimate.

Upvotes: 1

WhiZTiM
WhiZTiM

Reputation: 21576

You use the member function capacity() to obtain the allocated capacity

std::vector<int> abc;
abc.reserve(7);
std::cout << abc.capacity() << std::endl;

To get the memory allocated by in bytes, You can do:

sizeof(int) * abc.capacity();

This is given, that you know your value_type is int. If you don't

sizeof(decltype(abc.back())) * abc.capacity();

Upvotes: 5

Sven Nilsson
Sven Nilsson

Reputation: 1869

Since std::vector can store complex objects (such as std::string), which have their internal memory management and may allocate additional memory, determining the total memory usage can be hard.

For a vector containing simple objects such as int, the suggested solution using capacity and sizeof will work though.

Upvotes: 0

mksteve
mksteve

Reputation: 13073

There are strong statements on the memory being contiguous, and so the size is

sizeof( abc[0] ) * abc.capacity();

or

(  (char*)(&abc[1]) - (char*)(&abc[0] ) ) * abc.capacity();

Upvotes: 0

Jesper Juhl
Jesper Juhl

Reputation: 31447

Use the capacity member function - http://en.cppreference.com/w/cpp/container/vector/capacity

Upvotes: 0

Related Questions