B
Bill Pursell
I have a program that does most of its work traversing
a bunch of lists. The lists contain a void *, and I spent
some time today replacing the void *'s with a copy
of the data at the end of the structure as a zero length
array. The performance improvement that resulted by
avoiding the need to dereference the ptr was substantial,
but it has left me with an uncertain feeling. In particular,
changing an assignment caused the output to change,
and I'm not happy about it. The change that I think
should not have any affect is:
struct foo *f;
f = (struct foo *)&list_element->zdata;
becomes
struct foo f;
f = *(struct foo *)&list_element->zdata;
This is better described with the full program below.
My question is: 1) Are the final 3 assignments in this program
reliable?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct foo {
int x,y,z;
};
struct list_el {
void *data;
/* other stuff that throws off alignment */
/* gnu extension...*/
char zdata[] __attribute__((aligned(8)));
};
extern void * xmalloc(size_t s);
int
main(void)
{
struct list_el *L;
struct foo orig = {0,1,2};
struct foo *copy_ptr;
struct foo copy;
L = xmalloc(sizeof *L + sizeof orig);
L->data = &orig;
memcpy(&L->zdata, &orig, sizeof orig);
copy_ptr = (struct foo *)L->data;
copy_ptr = (struct foo *)&L->zdata;
copy = *(struct foo*)&L->zdata;
return EXIT_SUCCESS;
}
a bunch of lists. The lists contain a void *, and I spent
some time today replacing the void *'s with a copy
of the data at the end of the structure as a zero length
array. The performance improvement that resulted by
avoiding the need to dereference the ptr was substantial,
but it has left me with an uncertain feeling. In particular,
changing an assignment caused the output to change,
and I'm not happy about it. The change that I think
should not have any affect is:
struct foo *f;
f = (struct foo *)&list_element->zdata;
becomes
struct foo f;
f = *(struct foo *)&list_element->zdata;
This is better described with the full program below.
My question is: 1) Are the final 3 assignments in this program
reliable?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct foo {
int x,y,z;
};
struct list_el {
void *data;
/* other stuff that throws off alignment */
/* gnu extension...*/
char zdata[] __attribute__((aligned(8)));
};
extern void * xmalloc(size_t s);
int
main(void)
{
struct list_el *L;
struct foo orig = {0,1,2};
struct foo *copy_ptr;
struct foo copy;
L = xmalloc(sizeof *L + sizeof orig);
L->data = &orig;
memcpy(&L->zdata, &orig, sizeof orig);
copy_ptr = (struct foo *)L->data;
copy_ptr = (struct foo *)&L->zdata;
copy = *(struct foo*)&L->zdata;
return EXIT_SUCCESS;
}