eishiakonno
eishiakonno

Reputation: 73

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

This is an FCFC simulator program made using C. I am getting this certain error "Run-Time Check Failure #2 - Stack around the variable 'd' was corrupted." after I am finish entering all inputs for each process. What am I doing wrong?

void getdata()
{   
    char d;
    printf("Enter the number of process: ");
    scanf("%d",&n);

    printf("\nDo you need to enter the arrival time of process [Y/N]: ");
    scanf("%s",&d);
    printf("\n");

    for(int i=0; i<n; i++)
    {
        printf("*******************************************\n");
        printf("Enter the %d process burst time: ",i+1);
        scanf("%d",&b[i]);
        if(d=='y' || d=='Y')
        {
                printf("Enter the %d process arrival time: ",i+1);
                scanf("%d",&a[i]);
        }
        else
        {
                a[i]=0;
        }
    }
}

Upvotes: 0

Views: 1041

Answers (1)

hmjd
hmjd

Reputation: 121971

This is an error:

char d;
scanf("%s",&d);

as scanf("%s") will write to its argument until it locates whitespace and then appends a null terminator. d only has room for one character, meaning if there is at least one character then scanf() will be writing to memory it should not be causing some form of corruption. Use an array and limit the number of characters that can be read to prevent buffer overrun. For example:

char d[128];
scanf("%127s", d); /* One less than size to leave room for null terminator. */

Check the return value of scanf() (and all functions that returns a value indicating failure or success) to ensure d has actually been populated.


To avoid duplicating (essentially) the sizeof the array d in the scanf() format specifier, which is a maintenance overhead and error-prone, build the format specifier for reading d instead:

char d[128];
char d_format[32];
if (snprintf(d_format, sizeof(d_format), "%%%lus", sizeof(d) - 1) > 0)
{
    if (1 == scanf(d_format, d))
    {
    }
}

With this approach, if the sizeof() the array d is changed the format specifier for reading d will be automatically updated to the correct width (see demo @ http://ideone.com/9IsmgH).

Upvotes: 4

Related Questions