c++ - read() 缓冲区有无效数据(指针问题?)

标签 c++ c arrays pointers io

我遇到的问题是以下函数中的data 数组有一些糟糕的值(在我看来像是一些内存位置):

int
GPIO::GetValue() {
    char data[1];

    if (read(_valuefd, data, 1) < 0) {
        perror("Error on reading value fd");
        return -1;
    }

    printf("int GPIO::GetValue() %s\n", data);

    if (strcmp(data, "1") == 0) {
        return GPIO_VALUE_ON;
    }
    if (strcmp(data, "0") == 0) {
        return GPIO_VALUE_OFF;
    }

    return -1;
}

Full Source

printf的结果:

int GPIO::GetValue() 0cx$??ݾ??˶8@l

我不知道这是怎么回事。我在一些运行良好的简单程序中提取了相同的代码。还有一些其他函数 GPIO::GetDirection 可以执行相同的操作并且也可以正常工作。我猜有一些内存、指针、分配问题。

出了什么问题?

博多

最佳答案

我认为你得到了正确的结果。只是 null 终止字符串 data

char data[2];
data[1] = '\0';

实际上,您不需要声明数组。只需 char data; 就足够了。 那么您可能需要进行以下更改:

char data;
if (read(_valuefd, &data, 1) < 0) {
        perror("Error on reading value fd");
        return -1;
    }

printf("int GPIO::GetValue() %c\n", data);

if (data == '1') {
    return GPIO_VALUE_ON;
}
else if (data == '0') {
    return GPIO_VALUE_OFF;
}
else {
    return -1;
}

关于c++ - read() 缓冲区有无效数据(指针问题?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17183833/

相关文章:

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

c - 在 exec() 之后,child 继承了文件描述符,但流可能无法访问?

c# - 使用数组进行 XML 值测试

python - 如何使用for循环将2个列表/数组与python进行比较?

c++ - 请求 Pimpl 框架评论/建议

c++ - 在前一个完成之前再次调用 boost ASIO async_receive()

c++ - 如何声明或检查一对一函数?

c - C 中堆栈上的变量创建

c++ - 如何正确编译和链接 C 程序?

java - 从数组中选择随机元素,但唯一