簡體   English   中英

read()緩沖區具有無效數據(指針問題?)

[英]read() buffer has invalid data (pointer issue?)

我有一個問題,以下函數中的數據數組有一些糟糕的值(在我看來就像一些內存位置):

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;
}

完整資料

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;
}

“數據”數組的長度為1個字節。 如果要以字符串形式打印,則必須以“ \\ 0”結尾。 或者,嘗試使用%c代替%s。

printf("int GPIO::GetValue() %s\\n", data); 您嘗試顯示一個字符*。 但是由於數組的大小為1,printf不知道何時停止讀取,因為他找不到'\\ 0'。

printf("int GPIO::GetValue() %c\\n", data[0]); 如果您使用大小為1的數組

而且您的strcmp可能會失敗,請嘗試使用大小為1的strncmp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM