动态分配内存大小会导致堆栈崩溃错误

时间:2018-12-13 10:53:45

标签: c file strcat

情况很简单,但是我不知道为什么我溢出了缓冲区。我正在尝试打印文件的内容。将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);

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

在您的代码中

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

数组path仅为upload/和空终止符分配了空间(即,其大小适用于此)。将其用作strcat()的目的地将超出范围访问内存,这将导致undefined behavior

来自man page强调我的

  

strcat()函数将src字符串追加到dest字符串,覆盖'\0'末尾的终止空字节(dest),并且然后添加一个终止的空字节。字符串不能重叠,并且 dest字符串必须有足够的空间来容纳结果。如果dest不够大,则程序行为无法预测;

说,

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