运行时检查失败#2-变量'month1'周围的堆栈已损坏

时间:2018-12-04 21:48:02

标签: c++ visual-studio

我刚刚开始练习一些C ++进行考试,但遇到此错误,不知道如何解决? “运行时检查失败#2-变量'month1'周围的堆栈已损坏”

 here's my code: 
 #include <stdio.h>
 #include "pch.h"
 #include <iostream>
 #include <string.h> 

 int main()
 {
     char month[10] = "January";
     printf("%s\n", month);

     month[0] = 'J';
     month[1] = 'u';
     month[2] = 'l';
     month[3] = 'y';
     month[4] = '\0';
     printf("%s\n", month);


    char month1[10];
    printf("%s\n", month1);
    month1[0] = 'J';
    month1[1] = 'u';
    month1[2] = 'l';
    month1[3] = 'y';
    month1[4] = '\0';
    printf("%s\n" , month1);


    char month2[10];
    strcpy(month2, "April");
    printf("%s\n", month2);
    strcpy(month2, "Too many characters");
    printf("%s\n", month2);
     }

1 个答案:

答案 0 :(得分:0)

strcpy函数不会检查要复制到的字符数组是否足够大以容纳要复制的字符串。您的代码将导致缓冲区溢出。我不建议您这样做,除非您要尝试破解某些东西。

char month2[10];
strcpy(month2, "April");
printf("%s\n", month2);
strcpy(month2, "Too many characters"); // Buffer overrun.  Your string even hints at this.
printf("%s\n", month2);

您还将打印未初始化的字符串,这可能会导致其他问题。将printf与%s格式说明符一起使用将导致您传递的数组被视为以null终止的字符串。它将打印字符,直到达到0('\ 0'),这样输出的字符串可能会变得非常大。

char month1[10];
printf("%s\n", month1); // <- Printing uninitialized string