Search code examples
cruntime-errorautomaton

Stack around the variable 'userStr' was corrupted (C)


I've tried looking this up, and every single one seems to have a completely different answer.

I have this REPL function that compares a user's string input to a deterministic finite automaton (DFA), and that runs perfectly fine.

void REPL(DFA userDFA)
{
    char userStr[] = {'0'};
    printf("\nWhat string would you like to use?\n");
    scanf("%s", userStr);
    if (DFA_execute(userDFA, userStr))
        printf("\nAccepted\n");
    else
        printf("\nRejected\n");
} //program crashes right here

int main(void){...}

However, as soon as it reaches the end of the function, the program crashes and gives me the following error:

Run-Time Check Failure #2 - Stack around the variable 'userStr' was corrupted.


Solution

  • char userStr[] = {'0'};
    

    This means that userStr can only hold a single value; including the terminator. You haven't specified the size, so it looked at what you had in the {}. You only have a single element in there, so that's what size it used. Writing off the end of the array though into the memory that comes after it will corrupt the stack (because it's holding important stuff, like return addresses and other data).

    Specify the size to allow it to hold more:

    char userStr[100] = {'0'};
    

    This is giving it an arbitrary size of 100 long. You may need to give it a larger size, or use dynamic memory allocation (malloc and the like) to allocate to a size that's known at runtime.