I'm working through some example code from Understanding Unix/Linux Programming (Bruce Molay). There is an array declared to hold utmp structs:
#define NRECS 16
#define NULLUT ((struct utmp *)NULL)
#define UTSIZE (sizeof(struct utmp))
static char utmpbuf[NRECS * UTSIZE];
Why would one chose to declare the array type as char and not as struct utmp as shown below?
static struct utmp utmpbuf[NRECS];
The actual book source is here:
This code is probably bugged. The storage should be:
static struct utmp utmpbuf[NRECS];
as you suggested. As to why the book wrote this, you'd have to ask them about it. I don't see any conceivable reason.
The problem comes about from attempting to alias the char array as struct utmp:
recp = ( struct utmp *) &utmpbuf[cur_rec * UTSIZE];
Firstly, the char array might not be correctly aligned for struct utmp. If it is not correctly aligned, this cast causes undefined behaviour.
Even if it is correctly aligned however, any attempt to use *recp, or do recp->X where X is not a character type, would cause undefined behaviour by violating the strict aliasing rule. This code doesn't do that, but presumably the calling code that uses this function will dereference the returned pointer at some stage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With