I’ve a small problem with the code below. It is a simple program which reads in 2 arrays of char and an int. Then it stores all the content into another string and prints it out.
#include <stdio.h>
#include <string.h>
int main ()
{
char string [50];
char first [11];
char last [16];
int age = 0;
printf("Please type in your first name: ");
scanf("%s", first);
printf("Please type in your last name: ");
scanf("%s", last);
printf("Please type in your age: ");
scanf("%d", &age);
sprintf(string, "Your name is %s %s and you are %d years old.", first, last, age);
puts(string);
getchar();
getchar();
return 0;
}
Now the program is running fine, but when i close it, i get the following error:
Run-Time Check Failure #2 – Stack around the variable ‘string’ was corrupted.
That’s a bit confusing and i can’t figure out where the problem is. I would be thankful for
any advice.
You are writing more characters into ‘string’ than it has room allocated for (i.e. more than 50)
There are 37 characters in
"Your name is %s %s and you are %d years old."BEFORE you add the values for first, last and age. That leaves just 13 chars for all three variables. So it spills over into the other vars declared after your variable ‘string’ on the stack.As Jon mentioned, it is best practice to use the functions that limit how much they write (the ‘n’ variants), otherwise these can be sources of bufferoverrun exploits.
BTW ‘string’ is a very poor name for a variable.