Nodisplayname
Nodisplayname

Reputation: 23

Where exactly are variables stored while vectors store in RAM?

I used this and compiled it:

#include <iostream>
#include <string>
#include <vector>

int main() {

    std::vector<std::string> articles (119999999,"ads");
    std::cout <<   articles[1];
    getchar();
    return 0;
}

Then a memory error occurred that the memory is full (because no loss of information occurred). I opened the task manager and then I opened the program again. The program was consuming 250 megabytes, then my computer suddenly shutdown. I asked myself why when I declare many variables and arrays, there is no memory error.

So much so that I wrote a program to create a text file and then write thousands of variables and then I translated that file and the program opened normally!

Where are variables stored? And are vectors stored in RAM only?

Upvotes: 2

Views: 164

Answers (1)

Bathsheba
Bathsheba

Reputation: 234715

sizeof(std::string) is typically 32 bytes. Even with short string optimisation, the memory request is a contiguous block of 119999999 * 32 bytes. That's of the order of 4Gb and beyond the capability of your computer.

If you require the storage of duplicate strings then consider std::reference_wrapper as the vector element type.

Upvotes: 2

Related Questions