Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing with char *, unsigned char * and signed char *

A char * (and qualified variants) may alias anything. Are signed char * and unsigned char * (and their qualified variants) exempt from this?

In other words, I've learned it's a good idea to apply restrict to char* function arguments if I don't expect them to alias pointer parameters of other types (because they could alias them):

int func(struct foo *f, char * restrict s /*different object*/);

can I drop the restrict keyword for signed and unsigned char variants like so?

int sfunc(struct foo *f, signed char *s /*different object*/);
int ufunc(struct foo *f, unsigned char *s /*different object*/);

Also may pointers to a signed and unsigned variant of the same type alias each other? In other words if I expect a pointer to an int and a pointer to an unsigned and they should point to different objects, should the int * and unsigned * parameters each be restrict-qualified?

/* i and u should be different */
int uifunc(int * /*restrict?*/ i, unsigned * /*restrict?*/ u); 
like image 550
PSkocik Avatar asked Nov 13 '16 14:11

PSkocik


1 Answers

The rule is (C11 6.5/7):

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

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

char, signed char and unsigned char are all character types (ref: 6.2.5/15). The earlier bullets also answer your question about signed and unsigned types.

Bear in mind that the fixed width types are typedefs which may refer to various other types, so take care there.

like image 157
M.M Avatar answered Sep 25 '22 11:09

M.M