Is it possible to have a Segmentation Fault on if incorrectly set the value of a function pointer?
Or will the interpreter/compiler detect that beforehand?
The details depend on the language you're using, but in general it's not just possible but likely.
C provides no guarantees whatsoever. You can just say e.g.
#include <stddef.h>
typedef void (*foo)( void );
int main( void ) {
((foo)NULL)( );
return 0;
}
which takes NULL, casts it to a function and calls it (or at least attempts to, and crashes.) As of writing, both gcc -Wall and clang -Wall will neither detect nor warn for even this pathological case.
With other languages, there may be more safeguards in place. But generally, don't expect your program to survive a bad function pointer.
void (*ptr)() = (void (*) ())0x0;
ptr();
Nothing prevents you from compiling/executing this, but it will fail for sure.
The following example produces the segmentation fault you mention:
int main(int argc, char *argv[]) {
void (*fun_ptr)() = (void (*)()) 1;
(*fun_ptr)();
return 0;
}
None of cc, clang, splint issue a warning. C assumes that the programmer knows what he is doing.
UPDATE
The following reference illustrates why a C allows for absolute memory addressing to be accessed through pointers.
Koenig, Andrew R., C Traps an Pitfalls, Bell Telephone Laboratories, Murray Hill, New Jersey, Technical Memorandum, 2.1. Understanding Declarations:
I once talked to someone who was writing a C program that was going to run stand-alone in a small microprocessor. When this machine was switched on, the hardware would call the subroutine whose address was stored in location 0.
In order to simulate turning power on, we had to devise a C statement that would call this subroutine explicitly. After some thought, we came up with the following:
(*(void(*)())0)();
size_t (*funcptr)(int fd, void *buf, size_t count). Thefuncptrcan be set toreadbut not tostrcpy. The compiler will detect it.