Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 views
in Technique[技术] by (71.8m points)

c - Incrementing function pointers

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 it is stored in memory.

Is the machine code stored consecutively in memory, so that it is possible to "manually" increase the pointer until it points to the following/previous function?

Is this, what a debugger does? He lets me "see" where the program counter is pointing in the machine code?

Conclusion: one can program with function pointers a primitive debugger?

Did I understand this right, or am I way off?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using a draft C standard that I've managed to track down (N1124), we have similar rules. The section on addition expressions (§6.5.6/2) says that

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type

And an object type is defined in §6.2.5/1 as

The meaning of a value stored in an object or returned by a function is determined by the type of the expression used to access it. (An identifier declared to be an object is the simplest such expression; the type is specified in the declaration of the identifier.) Types are partitioned into object types (types that fully describe objects), function types (types that describe functions), and incomplete types (types that describe objects but lack information needed to determine their sizes).

Since function types are distinct from object types, this suggests that pointer arithmetic on function pointers is prohibited.

In C++, this operation is illegal. The definition of pointer addition, given in §5.7/1, says the following:

For addition, either both operands shall have arithmetic or enumeration type, or one operand shall be a pointer to a completely defined object type and the other shall have integral or enumeration type.

However, §3.9/9 states that

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.

Taken together, this means that you cannot increment a function pointer in C++.

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...