Search code examples
c++arraysstringoverflowbounds

C++ String Overflow


Here's a modified version of code from page 586 of "Starting Out With C++ - From Control Structures through Objects, 6e":

#include <iostream>
using namespace std;

int countChars(char *, char);

int main()
{
    const int SIZE = 5;
    char userString[SIZE];
    char letter;

    cout << "Enter a string: ";
    cin.getline(userString, 10);

    letter = '\0';
    cout << "a appears ";
    cout << countChars(userString, 'a') << " times.\n";

    cin >> letter;
    return 0;
}

int countChars(char *strPtr, char ch)
{
    int times = 0;
    while (*strPtr != '\0')
    {
        if (*strPtr == ch)
            times++;
        strPtr++;
    }
    return times;
}

Now run the program and enter "aaaabba".

Now, I have specifically tried to introduce incorrect writing to memory here. E.g. I declare that the char array size is 5, but enter more than 4 (5 minus the length of \0) characters when prompted.

Assuming that the system allocated memory for "letter" right after "userString", then it follows that when I write something to "letter" it should overwrite the corresponding location in the "extended" userString.

So the memory should look like this: [a][a][a][a][\0][b][a][\0].

Then when I run the countChars function, it, according to the book, should stop at the '\0' character, which is right after the first four a's.

By this logic, it should output that there are 4 a's in the string.

In reality, the program says there are 5 a's.

Where is the error in my reasoning?

EDIT #1: This is NOT a code from the book. It's MODIFIED code.

EDIT #2: I changed the code specifically to introduce a string overflow. I did this on purpose because I want to see if the memory actually works the way I think it does. So what I want to hear is a solid explanation about why the bug doesn't work as I expect it to.

EDIT #3: The compiler does complain about corrupted stack, but I press "continue" because I want to see what happens.

Thank you.


Solution

  • There is no rule in C or C++ that local variables be allocated in any particular order. Or even be on the stack at all. Your char may exist only in a CPU register. It might come before the array. The array size might be padded to the nearest 16 bytes to make things easier for SSE operations.