I received the error message: Run-Time Check Failure # 2. The stack around the variable was corrupted. However, I was not out of bounds to any picture

advertisements

I've been doing some exercise with structures to prepare for my upcoming exams, and I've run into a bit of trouble with this code.

// Creates a structure of type 'person' with a first name (nameF), last name (nameL), and the age (age)

typedef struct {
    char nameF[20];
    int age;
    char nameL[40];

}person;

// Main function
int main() {
    person ppl[2];  // We are creating 3 "people", whose information shall be printed into the file

        // This loop takes user input to create the names and ages of 3 people
        int i;
        for (i = 0; i <= 2; i++) {
            printf("\nEnter first name %d: ", i+1);
            scanf("%s", &ppl[i].nameF);
            printf("%s\n", ppl[i].nameF);
        }
        printf("It worked\n");
        system("pause");

    return 0;
}

It runs fine, but when the program exits, I keep receiving an error message from the Debugger that states: "Run-Time Check Failure #2. Stack around the variable 'ppl' was corrupted."

So I looked it up on Stack Overflow, this error appears when you go outside the bounds of a string. I don't understand where in my code I'm going out of bounds.

Here's an example of the output:

Enter first name 1: 'Adolfo'
Adolfo

Enter first name 2: 'Cecilia'
Cecilia

Enter first name 3: 'Tim'
Tim
Press any key to continue...

And then the error message pops up.
As you can see none of my inputs exceed the maximum amount of characters for the variable 'nameF', so there should be no reason for me to receive the error.

I saw someone on Stack Overflow mention that instead of making a character array:

char nameF[20];

One should instead write use dynamic memory allocation:

char * nameF = malloc(<enough bites to support any input);

Unfortunately, I don;t quite have a grasp of memory allocation yet, and when I attempted this code, I received all sorts of other errors, and my program wouldn't even run.

What is the mistake?

Also, I am not sure if this information is important, but I wrote this code using Visual Studio in C.

Edit: "char * nameF[20]" to "char nameF[20]" that asterisk was a leftover from my previous attempts at fixing the code, sorry.


Why are you allocating two structures then filling it with three responses?

Also, scanf is very dangerous as it can easily be abused to overwrite past a buffer. Look for routines (or write one) that limits the input to the length of the string.

hint: scanf man page might lead you to a better version.