Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is an array of utmp structs defined as char in this example?

Tags:

c

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:

  • http://sites.harvard.edu/~lib215/reference/bookcode/code/ch02/utmplib.c
like image 812
Chris Snow Avatar asked Feb 03 '26 20:02

Chris Snow


1 Answers

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.

like image 86
M.M Avatar answered Feb 06 '26 12:02

M.M