我的代碼是segfaulting,我不知道什麼是錯的。我儘可能簡化了它,但仍然無法找到問題。C - 調用fclose轉儲內核()
C語言文件test.c的:test.txt的
#include <stdlib.h>
#include <stdio.h>
struct container {
void *A[3], *B[3], *C[3], *D[3];
int x, y, z;
};
int main (int argc, char* argv[]) {
struct container *cont = malloc (sizeof cont);
FILE* fh = fopen(argv[1], "r");
if(fh == NULL) return 0;
fscanf(fh, "%d %d", &cont->y, &cont->z);
fclose(fh);
free(cont);
return 0;
}
內容
1 1
執行和通過GDB運行:
$ gcc --version
gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gcc -Wall -g test.c && gdb a.out
GNU gdb (GDB) 7.6.1-ubuntu
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dberg/ITX/Cells/test/a.out...done.
(gdb) break 26
Breakpoint 1 at 0x400739: file test.c, line 26.
(gdb) run test.txt
Starting program: /home/dberg/ITX/Cells/test/a.out test.txt
Breakpoint 1, main (argc=2, argv=0x7fffffffdf48) at test.c:26
26 fclose(fh);
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
__GI___libc_free (mem=0x1) at malloc.c:2892
2892 malloc.c: No such file or directory.
(gdb)
刪除未使用的結構成員中的任何一個允許代碼無誤地執行。將任何未使用的結構成員移動到結構的結尾或減小任何1或全部數組的大小也允許代碼成功執行。 fscanf()調用的存在對於段錯誤也是必需的
我的語法錯在哪裏,爲什麼結構的大小對這個錯誤至關重要?
提示:什麼是'sizeof cont'? – Mysticial
順便說一句:很好的問題。 – chux