我的代码有段错误,我不知道出了什么问题。我已经尽可能地简化了它,但仍然找不到问题。
C 文件 test.c:
#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;
}
test.txt 的内容
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() 调用的存在
我的语法哪里错了,为什么结构的大小对这个错误如此重要?