0

I am working on some legacy C program. It is some 20 years old version of C, and some old Unix OS (I am not familiar with the exact versions). Anyway, I need to write an xml file, so I wrote the program here at my Ubuntu machine, and when I started it there on that old system, I got some garbage at the end of my xml , which looks like a rectangle with something like:

0 0 
1 A

The problem is that I cannot reproduce it here at Ubuntu, probably the newer C can handle the case. My guess is that the problem is related to string terminating character \0. I 'm just not sure where is it happening, so I would like to have as much as possible ideas tomorrow, when I arrive there to fix it. Finally, my question is, do you think it is possible that the problem is newline \n, at the last fprintf? Or, may the following be a problem:

char name[50]; //this is read from file at some point
char first[50];
char last[50];
strcpy(first,strtok(name, " "));
strcpy(last,strtok(NULL, " "));

Thanks in advance.

zbs
  • 671
  • 4
  • 16

1 Answers1

0

You can try:

strncpy(first,strtok(name, " "),50);
strncpy(last,strtok(NULL, " "),50);

this will take care of the \0 if for some reason name does not contain \0 in its 50 characters.

Generally it is a better tactic to use strncpy than strcpy.

In normal execution their behave the same way. The difference is that during an overflow situation strncpy will protect you other variables and terminate the string correctly with a \0 while strcpy will fail to do so resulting in memory overflow and non-terminating strings.

zbs
  • 671
  • 4
  • 16