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() %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
相关文章:
- 链表指针问题
- 指针问题:从不兼容的类型"int"分配给"int *"
- C++指针问题:如何修复这些代码中的错误?
- *++*++ppp,*++pp[1],*++(*(1+ppp)有什么具体的区别吗?(C/C++指针问题)
- C++ 入门加列表:10.9 "顶部"指针问题
- C++ 指针问题 - 通过方法更新指针
- 未分配正在释放的指针 - 指针问题
- 双指针问题通过函数传递错误
- 在C++中实现图形 DFS,指针问题
- 返回指针问题
- C++ - 有人有分析指针到指针问题的技巧吗?
- 选择排序指针问题
- 涉及删除操作的 C++ 指针问题
- 模板类指针问题 c++
- Swig和指针问题(python)
- 引用指针问题
- 函数指针问题
- 通过类型C++ 的继承树递归导致此指针问题
- 无法将文件读入字符数组(像往常一样,某些指针问题)
- 结构中的指针问题