Curnelious Curnelious - 2 months ago 18
C Question

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.

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).

When I print
p
, usually its ok, but sometimes, only once in a while, I get this :

404C494748543B
X
@LIGHT;
��
@LIGHT;

��03


Which includes some previous data + garbage .

Is there something wrong with the way I extract the data ?

Answer

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.

The best way to diagnose and fix this problem is to run your code through a memory profiler, such as valgrind.

Note: There are two situations when your loop ends:

  • count reaches 2 (normal exit), or
  • p is set to NULL (on a break)

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.

Comments