局部变量的fread分割错误

时间:2016-05-15 00:52:42

标签: c random segmentation-fault fread

使用以下程序,我在调用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

我没有看到我如何使用指针错误...它是堆栈上的局部变量,保证是一个固定大小的有效位置...特别是因为它在最终失败之前工作了几次。我错过了什么?

1 个答案:

答案 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>