动态分配内存大小导致堆栈粉碎错误

Assigning memory size dynamically causes stack smashing error

情况很简单,但我不知道为什么会溢出缓冲区。我正在尝试打印出文件的内容。将 static int 分配给 count 是可行的,但任何找出文件大小的方法都会导致出现此错误并退出程序。

来源:

char path[] = "upload/";
strcat(path, filename);

FILE *file;

file = fopen(path, "r");
fseek(file, 0, SEEK_END);
int count = ftell(file);
printf("%d\n",count);
char *buffer = malloc(count);

fseek(file, 0, SEEK_SET);


fread(buffer, count, 1, file);
printf("%s\n", buffer);
free(buffer);
fclose(file);

如有任何帮助,我们将不胜感激!

在你的代码中

char path[] = "upload/";
strcat(path, filename);

数组 path 只为 upload/ 和空终止符分配了 space(即大小为)。将其用作 strcat() 的目标是越界访问内存,这会导致 undefined behavior.

来自man page强调我的

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

也就是说,

  • ftell()returns一个long,你应该相应地改变count的类型。
  • 在使用返回值之前,您应该始终检查函数调用的返回值是否成功。