Hacker News new | ask | show | jobs
by drt1245 3323 days ago
Additionally, he keeps talking about dereferencing the pointer, which I don't think is right. The pointer never gets deferenced in the code shown.

I'm not an x86 guru, but I think that "movq ptr(%rip), %rsi" is different because ptr needs to be moved from relative to the instruction pointer (because it is on the stack, as a non-const variable).

4 comments

It's a global variable, it's not on the stack. It's in the data section.

$arr is copying the address of "arr", so it must use an immediate move (possibly 64-bit). It could also use RIP-relative with the "lea" (load effective address) instruction.

$ptr(%rip) is accessing memory, so it uses RIP-relative addressing with the "mov" instruction.

> It's a global variable, it's not on the stack. It's in the data section.

And because it's a const, it's in the .rodata section... (read-only) Playing too liberally with the data often leads to a SEGV (as it should).

The code is more interesting if you -do- actually dereference the pointer, too. I've changed the prototype of "bogus" to take a single char as the first argument, and dereference the two pointers inside the do_arr/do_ptr functions:

https://goo.gl/jZYx0f

So the "do_arr" version "knows" what value is at * arr because "arr" is immutable, so the compiler can just choose to load a constant. The "do_ptr" version has to load from memory instead.

But what if we tell the compiler that the value of "ptr" won't change (i.e. "char * const" instead of "const char * ")? The code becomes the same:

https://goo.gl/iNaUHe

So basically "const char []" and "char * const" are more logically equivalent here.

This is a little off topic, but does anyone have any good resources to help me wrap my head around pointers in C? Right now they are very confusing to me.
Imagine all memory is a big array. A pointer is just an index into that array. A pointer dereference is like accessing something at an array index. A pointer to a pointer is array index to a location where you'll find another array index.
I understand pointers conceptually. It's the syntax (in C specifically) that is giving me trouble. I am fine with pointers in ASM.
Hmm, it's been a long time since I read it, but this sounds like something that good old K&R probably does well. It's famously short and well-written.

It's old-fashioned but I assume (maybe others can correct me) the latest edition is up to date enough that it won't teach you any outright bad habits.

Thank you very much! I'll give it a look.
You are right. This is RIP-relative addressing.