X
Xavier Roche
Hi folks!
My understanding of the aliasing rules is that a pointer to a char may
alias any other pointer type. The following trivial example is therefore
defined in C:
static void printBytes(const char *bytes, size_t size) {
size_t i;
for(i = 0 ; i < size ; i++) {
printf("byte [%zu] == %d\n", i, bytes);
}
}
....
const double foo = 42.0;
printBytes((char*) &foo, sizeof(foo)); /* print bytes of foo */
However, when using a pointer to void to transition to a pointer to a
char, is the aliasing rule still unviolated ?
Ie. the following code, which does not require any cast in user code,
but casts inside the function:
static void printBytes(const void *ptr, size_t size) {
const char *const bytes = (const char*) ptr;
size_t i;
for(i = 0 ; i < size ; i++) {
printf("byte [%zu] == %d\n", i, bytes);
}
}
....
const double foo = 42.0;
printBytes(&foo, sizeof(foo));
My understanding is that a "pointer to void" may be casted to anything,
but aliasing rules apply on "both sides" to the pointer -- ie. when
casting from A* to void*, then from the same void* to B*, the aliasing
rules between A* and B* apply.
Am I correct ?
(This would allow to write functions such as memset() in a non-undefined
behavior way)
My understanding of the aliasing rules is that a pointer to a char may
alias any other pointer type. The following trivial example is therefore
defined in C:
static void printBytes(const char *bytes, size_t size) {
size_t i;
for(i = 0 ; i < size ; i++) {
printf("byte [%zu] == %d\n", i, bytes);
}
}
....
const double foo = 42.0;
printBytes((char*) &foo, sizeof(foo)); /* print bytes of foo */
However, when using a pointer to void to transition to a pointer to a
char, is the aliasing rule still unviolated ?
Ie. the following code, which does not require any cast in user code,
but casts inside the function:
static void printBytes(const void *ptr, size_t size) {
const char *const bytes = (const char*) ptr;
size_t i;
for(i = 0 ; i < size ; i++) {
printf("byte [%zu] == %d\n", i, bytes);
}
}
....
const double foo = 42.0;
printBytes(&foo, sizeof(foo));
My understanding is that a "pointer to void" may be casted to anything,
but aliasing rules apply on "both sides" to the pointer -- ie. when
casting from A* to void*, then from the same void* to B*, the aliasing
rules between A* and B* apply.
Am I correct ?
(This would allow to write functions such as memset() in a non-undefined
behavior way)