Question

I came across a very strange error where the size of std::vector changes after receiving std::cin input. I've isolated the problem, but I don't understand why this happens:

int main()
{
    std::vector<int> asdf;
    asdf.push_back(1);
    asdf.push_back(42);

    printf("Size: %d\n",asdf.size());   //prints 2...

    char buffer[4];
    printf("Input 4 random characters:");
    std::cin >> buffer;

    printf("\n%d\n",asdf.size());     //prints 32???
}

When i commented std::cin >> buffer;, the error did not occur. Could anyone indicate why this happens? Is this due to some connection between vector and iostream? I am very confused...

Was it helpful?

Solution 2

Last character in buffer is reserved for \0. So if you enter 4 chars, the last char goes out of the reserved space of buffer which may turn out to be used by asdf. So basically it overwrites a part of asdf.

OTHER TIPS

You need 4 characters, and a NULL character after them, but you have a array with 4 characters. So change the array to char buffer[5];

Why this problem occurs? After entering 4 characters, it will put them in buffer[0],buffer[1],buffer[2],buffer[3] and finally it will put a NULL in buffer[4]. But you didn't have a place for buffer[4], so it will be written in a space which is related to the vector instance. This makes a change in your vector. You'r stack memory is something like this:

| ... Vector Instance Memory... | buffer[3] | buffer[2] | buffer[1] | buffer[0] |
                               ^this is the place where buffer[4] refers to

What you have encountered is called a buffer overrun. You reserved space for x characters, however x+1 characters were placed there.

Unlike other languages, C++ doesn't warn you that you've gone over the edge. Instead the characters get placed at their respective positions, as if the array is boundless. Yes, you declared an array of 4, but that 4 only tells you the valid or safe entries (indexed from 0 to 3). Anything outside these bounds, well, you see what may happen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top