Getting error: Stack around the variable was corrupted

Getting error: Stack around the variable was corrupted

运行 以下程序,但出现

错误

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.

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

来自strcat()man page强调我的

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('[=15=]') 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; ....

解法:

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


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

在你的情况下 unzip[]="winzip32 -e -o -j"; 有 space 仅用于你的初始字符串,17 个字符 + 空终止符。 然后你的变量没有空间用指令添加字符:

strcat(unzip," ");
strcat(unzip,fmuFileName);
strcat(unzip," ");
strcat(unzip,path);

您可以更改为:

void fmuUnzip()
{
   char fmuFileName[100], path[100],strFinal[100];
   printf("Enter fmuFileName\n");
   gets(fmuFileName);

   printf("Enter path of the fmuFileName\n");
   gets(path);
   char *unzip = malloc(17+1+strlen(fmuFileName)+strlen(path)+1);
   strcpy(unzip, "winzip32 -e -o -j");
   strcat(unzip," ");
   strcat(unzip,fmuFileName);
   strcat(unzip," ");
   strcat(unzip,path);
}