c - 为什么在这个 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;
}
解决方案
推荐阅读
- clang-format - 如何禁用长 for 语句的中断缩进?
- android - 如何在 Xamarin 的新“Android 设备管理器”中禁用快速启动?
- html - 无法切换或关闭模式
- python-3.x - 如何从列表中检索对象名称并将其传递给函数以检索该对象属性?“str”对象没有属性
- tensorflow - Tensorflow - 具有单输入神经元的全连接神经网络
- xml - 欺骗 XSL 将具有特定属性的 XML 元素解释为 null 或空
- scp - 使用用户密码从本地到远程服务器的 scp 文件
- jquery - 无法在标签中显示 $.ajax 结果
- php - 如何使用 mysqli_fetch_all 从数据库中获取数据?
- asp.net - ASP .net Webforms 上的 Elmah 生成 HTTP 500.19 错误