我正在运行以下 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/