错误:变量'string'周围的堆栈已损坏

Ord*_*rdo 6 c

我在下面的代码中遇到了一个小问题.这是一个简单的程序,它读入2个char和int数组.然后它将所有内容存储到另一个字符串中并将其打印出来.

#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;
}
Run Code Online (Sandbox Code Playgroud)

现在程序运行正常,但是当我关闭它时,我收到以下错误: 运行时检查失败#2 - 变量'string'周围的堆栈已损坏. 这有点令人困惑,我无法弄清楚问题出在哪里.我会感谢任何建议.

Mit*_*eat 15

您在"字符串"中写入的字符多于分配空间的字符数(即超过50个)

"Your name is %s %s and you are %d years old."添加first,last和age的值之前,有37个字符.这为所有三个变量留下了13个字符.因此它会溢出到堆栈上变量"string"之后声明的其他变量中.

正如Jon所说,最佳做法是使用限制写入量的函数('n'变体),否则这些可能是缓冲区漏洞利用的来源.

BTW'string'是变量的一个非常差的名字.