显然,答案与
使用以下程序,我在调用fread:时出现分段错误
static FILE *randomFile = (FILE*)0;
static void myFunction() {
unsigned char rand;
unsigned int i;
[...]
for (i = 0; i < 1000; i++) {
//LINE 88 BELOW
fread(&rand, sizeof(unsigned char), 1, randomFile);
printf("all well?: %hun", (unsigned short) rand);
[...]
}
[...]
}
int main() {
int i;
randomFile = fopen("/dev/urandom", "rb");
if (randomFile == 0) {
return EXIT_FAILURE;
}
[...]
for (i = 0; i < 1000; i++) {
myFunction();
[...]
}
[...]
fclose(randomFile);
return EXIT_SUCCESS;
}
下面是gdb
的run
和backtrace
命令的输出
$ gdb a.out
[...]
(gdb) run
[...]
all well?: 5
all well?: 234
all well?: 9
all well?: 79
all well?: 26
all well?: 108
all well?: 21
all well?: 195
all well?: 192
all well?: 148
all well?: 64
all well?: 211
all well?: 245
all well?: 90
all well?: 173
all well?: 238
all well?: 167
all well?: 125
all well?: 14
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a9ec82 in free () from /lib64/libc.so.6
(gdb) bt
#0 0x00007ffff7a9ec82 in free () from /lib64/libc.so.6
#1 0x00007ffff7a96856 in __underflow () from /lib64/libc.so.6
#2 0x00007ffff7a945a8 in __GI__IO_file_xsgetn () from /lib64/libc.so.6
#3 0x00007ffff7a898e6 in fread () from /lib64/libc.so.6
#4 0x0000000000400b69 in myFunction ()
at FileName.c:88
#5 0x0000000000400ebc in main (argc=1, argv=0x7fffffffdfd8)
at FileName.c:173
我不明白我怎么会用错指针。。。它是堆栈上的一个局部变量,保证是一个固定大小的有效位置。。。尤其是因为它在最终失败之前工作了好几次。我错过了什么?
fread
或局部变量无关。我的实际代码看起来更像:
static void myFunction() {
unsigned char rand;
unsigned int i;
unsigned short int *buffer1 = malloc(sizeof(unsigned short int)*smallNumberBug);
unsigned short int *buffer2 = malloc(sizeof(unsigned short int)*smallNumberBug);
[...]
for (i = 0; i < 1000; i++) {
//LINE 88 BELOW
fread(&rand, sizeof(unsigned char), 1, randomFile);
printf("all well?: %hun", (unsigned short) rand);
[... modify buffer2 ...]
memcpy(buffer1, buffer2, sizeof(unsigned short int)*biggerNumber));
}
[...]
}
以某种方式写入不正确的内存位置导致本地堆栈。。。已解除分配。。。不确定这是怎么回事,但将smallNumberBug
更改为等于biggerNumber
解决了我的问题。