0

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?

1
  • The compiler will detect it beforehand. The function pointer can only be set to the names of functions that has the same prototype declaration as expected by the pointer. For example, you declared size_t (*funcptr)(int fd, void *buf, size_t count). The funcptr can be set to read but not to strcpy. The compiler will detect it. Commented May 8, 2015 at 22:20

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for an example. That's deliberate and definitely possible. I'm guessing the OP is thinking more of non-deliberate program bugs.
2
void  (*ptr)() = (void (*) ())0x0;
ptr();

Nothing prevents you from compiling/executing this, but it will fail for sure.

1 Comment

That's deliberate. I'm guessing the OP is asking for non-deliberate program bugs.
1

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)();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.