c - 读取失败并显示 EFAULT

标签 c linux

我正在运行以下 C 代码,尝试读取缓冲区中的内容 分配在调用者的堆栈上,但失败并出现 errno 14(错误地址)。

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

void wrapper(int fd, char **buf)
{
  int res = read(fd, *buf, 10);

  printf("res: %d, errno: %d\n", res, errno);

  printf("Buf: %s\n", *buf);
}

int main()
{
  char buffer[10];

  memset(buffer, 0, 10);

  int fd = open("main.c", O_RDONLY);

  wrapper(fd, (char **)&buffer);

  return 0;
}

输出为

res: -1, errno: 14
Buf: (null)

我一直在寻找失败原因的解释,同时将其更改为

void wrapper(int fd, char *buf)
...
wrapper(fd, (char *)buffer);

有效,但到目前为止还没有结果。

最佳答案

why it fails

数组不是指针。 buffer 不是 char*。因此,&buffer 不是 char**,与 char** 不兼容,并且不应转换为 char* *。如果将其转换为 char** 然后取消引用,则行为未定义。

关于c - 读取失败并显示 EFAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255082/

相关文章:

c - 使用 extern 和 #including 头文件有什么区别?

java - Linux 和 Windows 上的 Jasper 是否有通用的字体格式来生成 pdf?

linux - 发送数据时是否可以选择网络适配器

c - 初始化程序不是常量...我知道,但我觉得这应该可以,为什么不行

c - C中的冒泡排序文件

c - array[1][2] 和 array[1,2] 有什么区别?

c - 如何检查Kgdb是否启用?

linux - 从 Linux shell 将多个目录复制到另一个多个目录

java - 使用 Mono 而不是 Java 的主要好处是什么?

linux - 如何在Linux shell脚本中搜索pdf文件的内容?