Error: the stack from the variable "string" was corrupted

I have a little problem with the code below. This is a simple program that is read in 2 char and int arrays. Then it saves all the contents to another line and prints it.

#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 works fine, but when I close it, I get the following error: Runtime check error # 2 - Damage to the variable "string" was damaged. This is a bit confusing and I cannot figure out where the problem is. I would appreciate any advice.

+5
source share
4 answers

You write more characters per line than for a dedicated room (i.e. more than 50)

"Your name is %s %s and you are %d years old." 37 . , . 13 . , vars, "string" .

, , , ( "n" ), bufferoverrun.

BTW 'string' - .

+13

, 10 15 . ( ), - , 66 - string 67 , ( ).

, , - , - 10 ( ..), . , C, "% 10s" "% 15s" fgets.

, snprintf ( snprintf_s, ) sprintf, . :)

+4

scanf

scanf("%9s", foo)

9 , NUL, 10.

+2

, , string 50 , sprintf 37 ( ), 11 first, 16 last, , , 2 3 . 50. , , , 50 . "", , .

+1
source

All Articles