使用以下程序,我在调用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?: %hu\n", (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
的{{1}}和run
命令的输出
backtrace
我没有看到我如何使用指针错误...它是堆栈上的局部变量,保证是一个固定大小的有效位置...特别是因为它在最终失败之前工作了几次。我错过了什么?
答案 0 :(得分:0)
显然答案与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?: %hu\n", (unsigned short) rand);
[... modify buffer2 ...]
memcpy(buffer1, buffer2, sizeof(unsigned short int)*biggerNumber));
}
[...]
}
写入不正确的内存位置导致本地堆栈被释放...不确定这是怎么回事,但将smallNumberBug
改为等于biggerNumber
解决了我的问题。< / p>