コードにセグメンテーション違反があり、何が問題なのかわかりません。できる限り単純化しましたが、まだ問題が見つかりません。
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 つまたはすべての配列のサイズを小さくすると、コードを正常に実行できます。segfault には fscanf() 呼び出しの存在も必要です。
構文のどこが間違っているのでしょうか? また、構造体のサイズがこのバグにとって非常に重要なのはなぜですか?