I had a short interview where a question is like this: set an integer value to be 0xaa55 at address 0x*****9.
The only thing I noticed is that the address given is not aligned on word boundary. So setting an int *p to the address should not work. Then is it just using a unsigned char *p to assign the value byte-wise? Is it the point of this interview question? There is no point of doing this in real life, is there?
You need to get back to the interviewer with a number of subsidiary questions:
int?The chances are that someone is thinking of marshalling data the quick and dirty way.
You’re right that one basic process is to write the bytes via a
char *orunsigned char *that is initialized to the relevant address. The answers to my subsidiary questions 1 and 2 determine the exact mechanism to use, but for a 2-byteintin little-endian format, you might use:You can generalize to 4-byte or 8-byte integers easily; handling big-endian integers is a bit more fiddly.
I assembled some timing code to see what the relative costs were. Tested on a MacBook Pro (2.3 GHz Intel Core i7, 16 GiB 1333 MHz DDR3 RAM, Mac OS X 10.7.5, home-built GCC 4.7.1), I got the following times for the non-optimized code:
When compiled with optimization, I got segmentation faults, even without
-DUSE_UNALIGNED— which puzzles me a bit. Debugging was not easy; there seemed to be a lot of aggressive inline optimization which meant that variables could not be printed by the debugger.The code is below. The
Clocktype and thetime.hheader (andtimer.csource) are not shown, but can be provided on request (see my profile). They provide high resolution timing across most platforms (Windows is shakiest).