c - 出现错误 : Stack around the variable was corrupted

标签 c runtime-error

运行以下程序但出现错误

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

什么可能导致错误?下面是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void fmuUnzip() {
  char fmuFileName[100], path[100],strFinal[100];
  char unzip[]="winzip32 -e -o -j";
  printf("Enter fmuFileName\n");
  gets(fmuFileName);

  printf("Enter path of the fmuFileName\n");
  gets(path);
  strcat(unzip," ");
  strcat(unzip,fmuFileName);
  strcat(unzip," ");
  strcat(unzip,path);
}

void fmuLoad() {
  fmuUnzip();
}

int main(int argc,char* argv[]) {
 fmuLoad();
}

最佳答案

这里的问题是(是)

strcat(unzip," ");   //problem starts here itself
strcat(unzip,fmuFileName);
strcat(unzip," ");
strcat(unzip,path);

因为,没有足够的内存来保存连接的字符串。本质上,您超出了分配的内存,它会调用 undefined behaviour .

当您定义一个未指定大小的数组并使用字符串对其进行初始化时,数组的有效大小将计算为字符串的长度,加上空终止符的长度。试图“猫”到那是内存溢出。

来自man page strcat()(强调我的)

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable; ....

解决方案:

定义一个足够大的目标数组来容纳连接的字符串,当然包括终止 null。

<小时/>

也就是说,gets()纯粹的邪恶,非常危险,因为它存在缓冲区溢出问题。您可能想使用fgets()相反。

关于c - 出现错误 : Stack around the variable was corrupted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31423333/

相关文章:

javascript - 如何使用 Javascript 向 MVC 中的 ModelState 添加错误消息?

c - 如何在C中使用UDP监听数据包?

c - 将委托(delegate)传递给 D 中的外部 C 函数

c - 错误 "malloc: *** error for object 0x7b: pointer being freed was not allocated"可能是什么原因

c++ - 为什么虚函数会出现段错误

android - 使用 AppCompatActivity 而不是 Actionbar 时出现运行时错误

C程序计算通过或失败的分数并在输入负数时退出

c - 当大的正数相乘时,为什么结果是负数?

c - 写入 c MPI 中的输出文件

Java jList NullPointerException 错误