user2793162
user2793162

Reputation:

Using unsigned char* with string methods such as strcpy

I recalled now at some places in my code I might have passed unsigned char* variables as parameters to functions such as strcpy and strtok -- which expect char *. My question is: is it a bad idea? Could it have caused issues?

e.g.

unsigned char * x = // .... some val, null terminated
unsigned char * y = // ... same here;
strcpy(x,y); // ps assuming there is space allocated for x

e.g., unsigned char * x = strtok(NULL,...)

Upvotes: 3

Views: 4698

Answers (3)

Deduplicator
Deduplicator

Reputation: 45674

The C aliasing rules have exceptions for signed/unsigned variants and for char access in general. So no trouble here.
Quote from the standard:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object,
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
— a character type.

All standard library functions treat any char arguments as unsigned char, so passing char*, unsigned char* or signed char* is treated the same.
Quote from the intro of <string.h>:

For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value).

Still, your compiler should complain if you get the signed-ness wrong, especially if you enable all warnings (you should, always).

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283733

It's guaranteed to be ok (after you cast the pointer), because the "Strict Aliasing Rule" has a special exception for looking at the same object via both signed and unsigned variants.

See here for the rule itself. Other answers on that page explain it.

Upvotes: 2

user2591612
user2591612

Reputation:

The only problem with converting unsigned char * into char * (or vice versa) is that it's supposed to be an error. Fix it with a cast.

e.g,

function((char *) buff, len);

That being said, strcpy needs to have the null-terminating character (\0) to properly work. The alternative is to use memcpy.

But you shouldn't use unsigned char arrays with string handling functions. In C strings are char arrays, not unsigned char arrays. Since passing to strcpy discards the unsigned qualifier, the compiler warns.

As a general rule, don't make things unsigned when you don't have to.

Upvotes: 0

Related Questions