user2534035
user2534035

Reputation:

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

I am trying to write a short simple C program where I am trying to store 5 numbers into an array and print them on screen.

Code is as following:

#define _CRT_SECURE_NO_WARNINGS 
#define size 5

#include <stdio.h>
#include <stdlib.h>

int main (void){

int i,input[size];

printf("Please enter %d numbers",size);
for (i=0; i<=size-1;++i);{
    scanf("%d",&input[i]);
printf ("Numbers you entered are: \n");
printf("%d",input[i]);}
return 0;
}

When I am inputting 1 2 3 4 5 as my 5 numbers to store them in array input[size], I am getting this following error :

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

I know error is something to do with array input[size] overflow. But I can't figure out how 1 2 3 4 5 are overflowing.

Thanks in advance.

Upvotes: 0

Views: 1156

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

You have an incorrect semicolon here:

for (i=0; i<=size-1;++i);{       // <---- Incorrect semicolon, braces
    scanf("%d",&input[i]);
printf ("Numbers you entered are: \n");
printf("%d",input[i]);}          // <---- ...closing brace here?

Your loop accomplishes nothing. After it completes, i==5, and the first value written by scanf is at input[5] (overrunning the buffer).

Additionally, your brackets make no sense and are not in the correct locations. If you want to first read 5 numbers, then print your message, then print those 5 numbers, you need to iterate twice.

So it is clear, here is your code, with standard indentation / bracket placement. It should be clear that it doesn't make any sense:

int main (void){
    int i, input[size];

    printf("Please enter %d numbers",size);
    for (i=0; i<=size-1; ++i)
    {
        // Do nothing
    }

    // i=5 now

    // Pointless block
    {
        scanf("%d",&input[i]);               // i=5, overrunning buffer
        printf ("Numbers you entered are: \n");
        printf("%d",input[i]);
    }

    return 0;
}

Here's what your code should look like (with proper indentation and brackets):

#define _CRT_SECURE_NO_WARNINGS 
#define SIZE 5

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int i;
    int input[SIZE];

    printf("Please enter %d numbers:\n",SIZE);
    for (i=0; i<=SIZE-1; ++i) {
        scanf("%d", &input[i]);
    }

    printf("\nNumbers you entered are: \n");
    for (i=0; i<=SIZE-1; ++i) {
        printf("%d\n", input[i]);
    }

    return 0;
}

Input/Output:

Please enter 5 numbers:
6
5
4
3
2

Numbers you entered are: 
6
5
4
3
2

Upvotes: 1

Related Questions