Home > Back-end >  Inline code with pointers and memory explanation
Inline code with pointers and memory explanation

Time:04-27

This was part of a code that is meant to dump the stack and show its layout in a book that was written years ago. Compile this code with -m32 (32bit) to avoid any warnings (Why?). I couldn't understand the below line, and since he doesn't cover that I come to ask StackOverflow.

  • What does the author try to achieve by this line?
unsigned int a, *x;
x = (unsigned int *) ((unsigned int) &a & ~0xf); // ..What?

By the way, if someone could name the above line and get a better title for me...

CodePudding user response:

Let's dissect the assignment:

  • &a is the address of a.
  • (unsigned int) &a casts it to an unsigned integer.
  • 0xf is an integer with the binary value 0...01111.
  • ~0xf is the bitwise complement of this, yielding all ones but the least four (1...10000).
  • ((unsigned int) &a & ~0xf) sets the least four bits of the address of a to zero by the "and" operator &. This will give you the address smaller than or equal to a's address that is divisible by 16 (0x10).
  • (unsigned int *) ((unsigned int) &a & ~0xf) casts this result back to a pointer to an unsigned integer.
  • x = (unsigned int *) ((unsigned int) &a & ~0xf); is the final assignment.

The intermediate cast is done, because the operator & works only with integers, not with pointers.

For example, if a's address is 0x123456, then x will receive 0x123450.

Why specifically this is done, I cannot say because the context is missing.

These casts only work as intended if the sizes of pointers and integers match. If you use another system, it will not necessarily work.

  •  Tags:  
  • c
  • Related