C-Kurs/Bus Error/Musterlösung: Unterschied zwischen den Versionen
Mario (Diskussion | Beiträge) K (Musterlösung) |
Mario (Diskussion | Beiträge) K (Freizeile ohne Freizeichen ....) |
||
Zeile 4: | Zeile 4: | ||
int an_int; | int an_int; | ||
}; | }; | ||
− | + | ||
struct header { | struct header { | ||
short id; | short id; | ||
char data[0]; | char data[0]; | ||
}; | }; | ||
− | + | ||
struct header * maker( int size ) { | struct header * maker( int size ) { | ||
return (struct header *)malloc( sizeof( struct header ) + size ); | return (struct header *)malloc( sizeof( struct header ) + size ); | ||
} | } | ||
− | + | ||
int main( void ) { | int main( void ) { | ||
struct header * a_headered_thing = maker( sizeof( struct thing ) ); | struct header * a_headered_thing = maker( sizeof( struct thing ) ); | ||
− | + | ||
struct thing * a_thing = (struct thing *)&(a_headered_thing->data[0]); | struct thing * a_thing = (struct thing *)&(a_headered_thing->data[0]); | ||
− | + | ||
a_thing->an_int = 42; | a_thing->an_int = 42; | ||
} | } |
Version vom 6. September 2010, 14:56 Uhr
Der Bus Error wurde bereits in der VL erwähnt. Hier ein Quellcodeauszug aus [1], der ihn erzeugt.
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_thing->an_int = 42; }