Incrementing function pointers

后端 未结 5 1292
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 15:36

I just learned about function pointers (pointers pointing at the adress where where the machine code of a function is stored). This made me think about machine code and how

5条回答
  •  感情败类
    2021-01-17 16:09

    Kind of. You are assuming functions will be layed out in memory the same way they are in the source code. Most likely, they will not be - the compiler usually moves them around all willy-nilly.

    What you could do, however, is step through the code with a pointer to the current instruction, and increment that counter by a certain amount to get to the next instruction. However, in that case we would no longer call it a function pointer, since it's not just pointing to the beginning of a function; instead, we'd call it an instruction pointer.

    In fact, this is exactly how a computer works - it has a special register called the program counter which always points to the current instruction, and increments it by a certain amount after every instruction (a GOTO command is equivalent to writing a value into the program counter).

    In the real world, however, this is not how debuggers work - in fact, I'm not even sure if it's possible to have a pointer point to the code-segment in memory in C, other than a function pointer. More likely, you would only need to use this technique if you needed to simulate a program counter, such as writing an emulator for another processor-type.

提交回复
热议问题