Skip to main content

Posts

Showing posts from April, 2007

Debugging: Solaris bus error caused by taking pointer to structure member

Take a look at this sample program that fails horribly when compiled on Solaris using gcc (I haven't tried other compilers, and I'm not pointing my finger at gcc here, this is a Sun gotcha). Here's an example program (simplified for something much more complex that I was debugging), that illustrates how memory alignment on SPARC systems can bite you if you are doing low-level things in C. In the example the program allocates space for a thing structure which will be prepended with a header . The header structure has a dummy byte array called data which will be used to reference the start of the thing . struct thing { int an_int; }; struct header { short id; char data[0]; }; struct header * maker( int size ) { return (struct header *)malloc( sizeof( struct header ) + size ); } int main( void ) { struct header * a_headered_thing = maker( sizeof( struct thing ) ); struct thing * a_thing = (struct thing *)&(a_headered_thing->data[0]); a_thi