首页 > 解决方案 > 为什么在这个 C 函数中出现“fread: EFAULT, bad address”?

问题描述

以下函数从 中读取任意数据stdin并一次生成一个unsigned int。如果找到EOF,则退出。如果文件是无限的(例如/dev/urandom),它将永远存在。我有一个大约 95 MiB 的文件,可以生成fread: Bad address. 你能看出为什么吗?

unsigned int generator(void)
{
  static unsigned int buffer[8192 / sizeof(unsigned int)];
  static unsigned int pos; /* where is our number? */
  static unsigned int limit; /* where does the data in the buffer end? */

  if (pos >= limit) {
    /* refill the buffer and continue by restarting at 0 */
    limit = fread(buffer, sizeof (unsigned int), sizeof buffer, stdin);

    if (limit == 0) {
      /* We read 0 bytes.  This either means we found EOF or we have
      an error.  A decent generator is infinite, so this should never
      happen. */
      if (ferror(stdin) != 0) {
        perror("fread"); exit(-1);
      }
      if (feof(stdin) != 0) {
        printf("generator produced eof\n");
        exit(0);
      }
    }

    pos = 0;

  }

  unsigned int random = buffer[pos]; /* get one */
  pos = pos + 1;
  return random;
}

标签: cunix

解决方案


推荐阅读