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

read() buffer has invalid data (pointer issue?)

本文关键字:指针 问题 数据 缓冲区 read 无效      更新时间:2023-10-16

我有一个问题,以下函数中的数据数组有一些糟糕的值(在我看来像一些内存位置(:

int
GPIO::GetValue() {
    char data[1];
    if (read(_valuefd, data, 1) < 0) {
        perror("Error on reading value fd");
        return -1;
    }
    printf("int GPIO::GetValue() %sn", data);
    if (strcmp(data, "1") == 0) {
        return GPIO_VALUE_ON;
    }
    if (strcmp(data, "0") == 0) {
        return GPIO_VALUE_OFF;
    }
    return -1;
}

完整来源

打印结果:

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

我不知道这出了什么问题。我在一些简单的程序中提取了相同的代码,它工作正常。还有一些其他函数GPIO::GetDirection,它做同样的事情,也可以正常工作。我想有一些内存,指针,分配问题。

出了什么问题?

博多语

我认为

你得到了正确的结果。只需 null 终止字符串data

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

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

char data;
if (read(_valuefd, &data, 1) < 0) {
        perror("Error on reading value fd");
        return -1;
    }
printf("int GPIO::GetValue() %cn", data);
if (data == '1') {
    return GPIO_VALUE_ON;
}
else if (data == '0') {
    return GPIO_VALUE_OFF;
}
else {
    return -1;
}

'data' 数组的长度为 1 字节。如果要将其打印为字符串,则必须以"\0"结尾。或者,尝试使用 %c 而不是 %s。

printf("int GPIO::GetValue() %sn", data); 您尝试显示字符*。但是由于你的数组大小为 1,printf 不知道什么时候停止读取,因为他找不到"\0"。

printf("int GPIO::GetValue() %cn", data[0]);如果您使用大小为 1 的数组

而且您的 strcmp 可能会失败,请尝试大小为 1 的 strncmp