运行以下程序但出现错误
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 thesrc
string to thedest
string, overwriting the terminating null byte ('\0'
) at the end ofdest
, and then adds a terminating null byte. The strings may not overlap, and thedest
string must have enough space for the result. Ifdest
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/