0

I'm preparing for a Computer Architecture exam, and I can't seem to answer this question:

The following code is useful in checking a memory-related ISA feature. What can you determine using this function?

#define X 0
#define Y 1

int mystery_test(){
        int i = 1;
        char *p = (char *) &i;
        if(p[0] == 1) return X;
        else return Y;
}

I was thinking that it would check that pointers and arrays are basically the same, but that isn't a memory-related feature so I'm pretty sure my answer is wrong.

Could someone help, please? And also, what are the memory-related ISA features?

Thank you!

juimdpp
  • 37
  • 1
  • 4
  • 1
    This code is checking whether the CPU is little-endian or big-endian – Steve Friedl Jun 15 '20 at 03:18
  • 1
    https://stackoverflow.com/questions/2100331/c-macro-definition-to-determine-big-endian-or-little-endian-machine – Retired Ninja Jun 15 '20 at 03:19
  • 1
    They're hoping you tell them about endianess. but the function also tells something else because of a bug in it. If it kill the process, you can tell you're on a machine with alignment restrictions. Unfortunately, it doesn't tell you anything about alignment restrictions if it doesn't kill the process. – ikegami Jun 15 '20 at 04:44

1 Answers1

0

The answer from Retired Ninja is way more than you ever want to know, but the shorter version is that the mystery code is testing the endian-ness of the CPU.

We all know that memory in modern CPUs is byte oriented, but when it's storing a larger item - say, a 4-byte integer - what order does it lay down the components?

Imagine the integer value 0x11223344, which is four separate bytes (0x11 .. 0x44). They can't all fit at a single byte memory address, so the CPU has to put them in some kind of order.

Little-endian means the low part - the 0x44 - is in the lowest memory address, while big-endian puts the most significant byte first; here we're pretending that it's stored at memory location 0x9000 (chosen at random):

        Little   Big -endian
0x9000: x44     x11
0x9001: x33     x22
0x9002: x22     x33
0x9003: x11     x44

It has to pick something, right?

The code you're considering is storing an integer 1 value into a 4 (or 8) byte chunk of memory, so it's going to be in one of these two organizations:

        Little  Big
0x9000: x01     x00   
0x9001: x00     x00
0x9002: x00     x00
0x9003: x00     x01

But by turning an integer pointer into a char pointer, it's looking at only the low byte, and the 0/1 value tells you if this is big-endian or little-endian.

Return is X/0 for little-endian or Y/1 for big-endian.

Good luck on your exam.

Steve Friedl
  • 3,929
  • 1
  • 23
  • 30
  • Re "*Returns is Y/1 for big-endian*", [Not necessarily.](https://en.wikipedia.org/wiki/Endianness#Middle) You merely know it's not little-endian, not that it's big-endian. – ikegami Jun 15 '20 at 04:39
  • @ikegami - fair point, especially for an architecture class. – Steve Friedl Jun 15 '20 at 04:46