Search code examples
c++stack-overflow

How does manipulation of a char array cause a stack overflow?


If there is a blatantly obvious flaw, I'm sorry. I'm fairly new to memory, so I have some understanding on how stack overflows work and as far as I know, nothing I'm doing should cause a stack overflow. All I'm doing is changing the character in a string.

I know arrays are pointers, but would changing the value cause a stack overflow?

Here is the concerning function:

char base[] = "aaaaa";
void changeLetters(int position) { // Stack overflow happens around here
    if (base[position] != 'z') {
        base[position]++;
    }

    // When I include a cout here, I also get a stack overflow

    if (position == 4 && base[position] != 'z') {
        changeLetters(position);
    }
    else if (base[position] == 'z' && position != 0) {
        base[position] = 'a';
        changeLetters(position - 1);
    }
    else if (position < 4) {
        changeLetters(position + 1);
    }
}

When not having std::cout, I get the

Unhandled exception at 0x767C3210 (KernelBase.dll) in passwordCracker.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x01002FFC).

Otherwise

Unhandled exception at 0x009C38B9 in passwordCracker.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x006D2F8C).

Edit: The function is called in the main loop. The value passed is the length of the string (4), and it works its way through. One odd thing I didn't mention is that it works perfectly if I cycle through a smaller amount of letters (a, b, c, d) but I only recieve a stack overflow if I have it cycle through the alphabet.


Solution

  • Your code is iterating over all strings of length 5 made up of the alphabet a-z. This is not a problem by itself, however you have to make sure that the maximal call depth is not too large.

    In each iteration of changeLetters you are increasing at most one letter once and then call again to changeLetters and you make at most one such call.

    Therefore your call graph is completely linear, for each of the 26^5 strings you are making another recursive call in depth and so the call stack at the end will be about that large. The problem is, that this is a very large number 26^5 = 11881376 and may easily be larger than the stack space you may use.

    You need to make the linear call graph into one with branches, by e.g. using a loop over the current character's position instead of calling changeLetters each time.