[英]Parsing a string prints garbage
I have this problem parsing a string, maybe you can help. 我在解析字符串时遇到此问题,也许您可以帮上忙。
I am not from a C field, so please try to be patient with the stupid things I do. 我不是C领域的人,所以请对我的愚蠢行为保持耐心。
I have this : 我有这个 :
#include <stdio.h>
#include <string.h>
char DataIn[65] = "WV,000B,404C494748543B.";
int main()
{
char *p = DataIn;
puts(DataIn);
for (int count = 0;count<2 ; ++count) {
p = strstr(p, ",");
if (!p )
break;
p++;
}
char *endPointer = strchr(p, '.');
*endPointer = '\0';
puts(p);
}
The output I want from this example is: 404C494748543B
(which can have different length). 我从此示例中获得的输出是:
404C494748543B
(可以具有不同的长度)。
When I print p
, usually its ok, but sometimes, only once in a while , I get this : 当我打印
p
, 通常可以 ,但是有时只有一段时间 ,我会得到:
404C494748543B
X
@LIGHT;
��
@LIGHT;
��03
Which includes some previous data + garbage . 其中包括一些先前的数据+垃圾。
Is there something wrong with the way I extract the data ? 我提取数据的方式有问题吗?
When things work most of the time, but sometimes you get garbage, it is undefined behavior. 当事情大部分时间都在起作用,但有时却会产生垃圾,这是未定义的行为。 This means that
DataIn
points to invalid memory - something that has been de-allocated, or is allocated on the stack of a function that has finished working. 这意味着
DataIn
指向无效的内存-已经取消分配的内存或已完成工作的函数的堆栈上分配的内存。
The best way to diagnose and fix this problem is to run your code through a memory profiler, such as valgrind . 诊断和解决此问题的最佳方法是通过内存分析器(例如valgrind)运行代码。
Note: There are two situations when your loop ends: 注意:循环结束有两种情况:
count
reaches 2 (normal exit), or count
达到2(正常退出),或 p
is set to NULL
(on a break) p
设置为NULL
(暂停) The code searching for endPointer
, however, assumes that p
is not NULL
without any checks, which means your program may crash when the loop exits on a break
. 但是,搜索
endPointer
的代码假定p
没有任何检查都不为NULL
,这意味着当循环在break
退出时,程序可能会崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.