#include <stdio.h> struct Bulb { int watts; int lumens; }; /* function to print a Bulb */ void printBulb( struct Bulb *b ) { printf("watts = %d\tlumens = %d\n", b->watts, b->lumens ); } int main(int argc, char *argv[]) { /* declare and initialize a Bulb pointer */ struct Bulb *bptr; /* allocate memory for the Bulb */ bptr = (struct Bulb*)malloc( sizeof(struct Bulb) ); /* initialize the Bulb */ bptr->watts = 100; bptr->lumens = 1530; /* print the Bulb */ printBulb( bptr ); /* deallocate memory */ free( bptr ); /* make a horrible mistake */ bptr->watts = 44; bptr->lumens = 505; printBulb( bptr ); system("pause"); return 0; }
Comments:
The sizeof
operator returns the size of the struct in bytes.
Always use sizeof
rather than a literal because the size of
a struct is not always the sum of the size of the individual members.
This is because of alignment restrictions that the compiler follows.
For example, the struct
struct OddBall { char x; int y; char z; };
is likely to require 12 bytes, not the 6 you might calculate.
The horrible mistake
is using dynamically allocated
memory after it has been free
ed.
This appears to work in the current program,
but there is no guarantee that it will always work.
Freeing memory informs the operating system that the
memory is available for reuse, but does not prevent you from
using it further.
But the operating system might also do something with the
memory and now things could get really confused.