【发布时间】:2021-03-05 03:37:42
【问题描述】:
这是我从 valgrind 得到的:
==1654036== Thread 102:
==1654036== Invalid read of size 1
==1654036== at 0x491328C: _IO_file_fopen@@GLIBC_2.2.5 (fileops.c:225)
==1654036== by 0x4905B0D: __fopen_internal (iofopen.c:75)
==1654036== by 0x4905B0D: fopen@@GLIBC_2.2.5 (iofopen.c:86)
==1654036== by 0x10A9EC: readFromDisk (in /home/john/OS4061/p3/group/p3/web_server)
==1654036== by 0x10AC72: worker (in /home/john/OS4061/p3/group/p3/web_server)
==1654036== by 0x4866608: start_thread (pthread_create.c:477)
==1654036== by 0x49A2292: clone (clone.S:95)
==1654036== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==1654036==
==1654036==
==1654036== Process terminating with default action of signal 11 (SIGSEGV)
==1654036== Access not within mapped region at address 0x0
==1654036== at 0x491328C: _IO_file_fopen@@GLIBC_2.2.5 (fileops.c:225)
==1654036== by 0x4905B0D: __fopen_internal (iofopen.c:75)
==1654036== by 0x4905B0D: fopen@@GLIBC_2.2.5 (iofopen.c:86)
==1654036== by 0x10A9EC: readFromDisk (in /home/john/OS4061/p3/group/p3/web_server)
==1654036== by 0x10AC72: worker (in /home/john/OS4061/p3/group/p3/web_server)
==1654036== by 0x4866608: start_thread (pthread_create.c:477)
==1654036== by 0x49A2292: clone (clone.S:95)
这里是函数
int readFromDisk(char *mybuf, char *request) {
int num_bytes = 0;
FILE *file = fopen(request, O_RDONLY);
if(file == NULL){
return 0;
}
while(fread(mybuf,1, 1, file)!=EOF){
num_bytes++;
}
return num_bytes;
}
我已尝试打印请求,它是有效的文件路径。
提前谢谢你。
【问题讨论】:
-
什么是
O_RDONLY?指定打开模式的字符串应该放在那里。请发布Minimal, Reproducible Example。一定要打开编译器警告。 -
O_RDONLY 是 open() 的参数,而不是 fopen()。你想要像 fopen(request, "r")
-
点评:为什么在
fread(mybuf,1, 1, file)!=EOF中使用EOF? -
@John 使用
-g然后运行 valgrind。这将为您提供确切的行号。日志中缺少行号。请看这个stackoverflow.com/questions/12130246/… -
阅读this。