views:

516

answers:

4

Given that all the primitive data types and objects have memory allocated, it is intuitively easy to imagine the pointers to these types.

But where exactly do function pointers point to? Given that instructions are converted into machine code and reside in memory, should we consider they point to the memory location corresponding to the start of the functions instructions?

We face many errors in pointers due to illegal memory access. Is it the case that errors occur when function pointers point to data memory instead of instruction memory?

+24  A: 

Function pointer also point into memory, the only difference is that there is executable code at that memory location instead of data.

On many platforms if you try to execute data (e.g. regular memory) you'll crash or cause an exception. This is known as Data Execution Prevention - a security measure to prevent applications inadvertently running dodgy code that may be placed there by malware.

Andrew Grant
+4  A: 

It's a code pointer. It points to the function's address. It is essentially as you described. And yes, if you have pointers that don't point to what you expect, you will have problems.

BobbyShaftoe
A: 

Well I'm not sure but considering that functions are instructions(ADD, SUB, JMP) and that each of them have hexadecimal values, I believe that you would not be altering the function but only the JMP instruction()...

Diones
If you are altering the JMP instruction, you have self-modifying code, which is usually considered black magic. Functions pointers are just like other pointers - an address stored in RAM; the JMP the gets it's target from the variable instead of data compiled into the program.
Justin Love
I think that there some CPUs that do all pointers in this way, by having the "pointer" be a value in the code, very simple PICs and DSPs for example.
Zan Lynx
I don't get it, where is the flaw in my line of thought?
Diones
Diones, the flaw is that function pointers are not normally implemented by rewriting a JMP instruction. That is only done on very *very* small CPUs. Normally the CPU uses some form of indirect branch instruction.
Zan Lynx
a compiler will not necessarily create self modifying code to implement function pointers, although there are some cases where it might. On Windows/IA-32 for instance you can allocate memory with VirtualAlloc and the PAGE_EXECUTE_READWRITE flag and and write byte code to that address and call it...
jheriko
+2  A: 

Function pointers point to the address of the function in memory.

Based on the way function pointers are usually assigned, I would be surprised if you had them pointing to a data location. They are not typically cast and so unlikely to point anywhere other than to a valid function. If you are casting them a lot, then this could be a problem. More likely though is that the data you are passing to the function is wrong.

Steve Rowe