Magisch
Magisch

Reputation: 7352

Safety of using \0 before the end of character arrays

I am writing a driver for an embedded system that runs a custom version of modified linux (Its a handscanner). The manufacturer supplys a custom Eclipse Juno distribution with a few libraries and examples inbound.

The output I receive from the comport comes in form of a standard character array. I am using the individual characters in the array to convey information (error ids and error codes) like this:

if (tmp[i] == 250])

Where tmp is a character array in form of char tmp[500]; that is first initialized to 0 and then filled with input from the comport.

My question is:

Assuming I iterate through every piece of the array, is it safe to use 0 (as in \0) at any point before the end of the Array? Assuming I am:

  1. Not treating it as a string (iterating through and using it like an int array)
  2. In knowledge of what is going to be in there and what exactly this random \0 in the middle of it is supposed to mean.

The reason im asking is because I had several coworkers tell me that I should never ever ever use a character array that contains \0 before the end, no matter the circumstances.

My code doing this currently performs as expected, but im unsure if it might cause problems later.

Rewriting it to avoid this behaviour would be a non-trivial chunk of work.

Upvotes: 5

Views: 90

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409482

Using an array of char as an array of small integers is perfectly fine. Just be careful not to pass it to any kind of function that expects "strings".

And if you want to be more explicit about it, and also make sure that the array is using unsigned char you could use uint8_t instead.

Upvotes: 7

Related Questions