请看下面的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
void main() {
struct stat file_st;
int size=0, ret=0;
char* buf=NULL;
FILE* file = fopen("newfile", "r");
if (file==NULL) {
printf("error");
exit(1);
}
if (stat("newfile", &file_st)!=0) {
printf("stat failed\n");
exit(1);
}
buf = (char*)malloc(sizeof(file_st.st_size+1));
buf[file_st.st_size]='\0';
ret = fread(buf, 1, file_st.st_size, file);
printf("fread return value is: %d\n");
ret = fclose(file);
printf("fclose return value: %d\n", ret);
printf("%s\n", buf);
}此代码通过编译,但在运行时崩溃。你知道为什么吗?
但是,如果我在fclose()和printf() (代码的最后两行)之间切换,那么代码将成功运行并打印"newfile“的内容。这两种情况的区别是什么?
发布于 2016-06-13 08:30:18
buf = (char*)malloc(sizeof(file_st.st_size+1));从此表达式中删除sizeof运算符。我很惊讶它能编译。它返回整数的大小,即4或8,而不是文件的大小。您正在溢出缓冲区。
此外,打印fclose()的返回值也是徒劳的。如果返回失败,则需要打印errno或strerror()。
发布于 2016-06-13 07:13:32
一个好的编译器至少会告诉你代码中的一个错误。来自gcc -Wall -O
a.c:24:5: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
printf("fread return value is: %d\n");
^根据您的环境,省略printf的参数可能会导致打印垃圾、崩溃、打印垃圾和崩溃、不打印任何东西和崩溃,或者打印垃圾或什么都不打印并使程序的内存处于损坏状态,从而导致某些操作失败。特别是,丢失的参数肯定可能会导致fclose崩溃,但如果在两者之间调用printf,则会将程序的内存恢复到有效状态。不可能确切地说会发生什么,因为这完全取决于程序在内存中是如何排列的,以及如何与操作系统的期望相匹配,以及编译器如何工作。在C语言中,当出现问题时,所有的赌注都会失效。
https://stackoverflow.com/questions/37762810
复制相似问题