What does the null function pointer in C mean?

Say we have a function pointer:

void (*func0)(void); 

which is also defined:

 void func0(void) { printf( "0\n" ); } 

But let's say, at some point we are trying to somehow access the function pointer, then if the MS VS debugger shows that func0 actually points to 0x0000, when I enter the code, what does this mean? And also please also let me know what is the best fix? Thanks.

+2
source share
2 answers

Undefined behavior cancels the reference to a null pointer. The fix is ​​to make sure the pointer refers to the corresponding function.

In your case, you want something like this:

 void MyFunction(void) { printf( "0\n" ); } 

and then you can assign func0 :

 func0 = &MyFunction; 

Note that I use a different name for the function pointer variable and the actual function.

And now you can call the function through the function pointer:

 func0(); 
+8
source

I think you are mixing names and defining function pointers. I will just point out that if you write

 void func0(void) { printf( "0\n" ); } void (*func0)(void); 

you actually have two completely unrelated objects with the same name func0 . The first func0 is a function, the second func0 is a variable with a type pointer.

Assuming you declared your func0 variable globally (outside of any function), it will be automatically zero initialized, so the compiler will read your line

 void (*func0)(void); 

but

 void (*func0)(void) = NULL; 

Thus, func0 will be initialized to NULL , and on most systems, NULL will actually be 0 .

Now your debugger tells you that your variable func0 has a value of 0x0000 , which is 0 . So this is really not a big surprise.

To your question regarding the β€œfix” - well, I assume that you need a pointer to a function that points to your func0 function, so you can do the following:

 void func0(void) { printf( "0\n" ); } void (*pFunc)(void) = func0; 

or even better (although most compilers do not need it), you can write

 void (*pFunc)(void) = &func0; 

so that you initialize the pFunc variable (I highly recommend renaming it!) to point to func0 . A little more precise: you take the address &... the func0 function and assign this value to your pFunc variable.

Now you can β€œcall” the function pointer (which means calling the function that the function pointer points to):

 pFunc(); //will call function func0 
+5
source

All Articles