Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL function pointers

Tags:

c++

c

c99

What is the behavior of calling a null function pointer?

void (*pFunc)(void) = NULL;  
pFunc();

Why is it advisable to initialize yet unused function pointers to NULL?

like image 854
Vorac Avatar asked Feb 26 '13 13:02

Vorac


People also ask

What is an example of a null pointer?

A null pointer constant is an integer constant expression that evaluates to zero. For example, a null pointer constant can be 0, 0L , or such an expression that can be cast to type (void *)0 .

Can pointers be null?

Programs routinely use null pointers to represent conditions such as the end of a list of unknown length or the failure to perform some action; this use of null pointers can be compared to nullable types and to the Nothing value in an option type.

How do you use null pointers?

Some uses of the null pointer are: a) To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet. b) To pass a null pointer to a function argument when we don't want to pass any valid memory address. c) To check for null pointer before accessing any pointer variable.

Can you return null in a pointer function?

A function that returns pointer values can return a null pointer when it is unable to perform its task. (A null pointer used in this way is analogous to the EOF value that functions like getchar return.) The start pointer steps over each character position in the input string.


1 Answers

In C and C++, this is called undefined behaviour, meaning that this can lead to a Segmentation fault, nothing or whatever such a case will cause based on your compiler, the operating system you're running this code on, the environment (etc...) means.

Initializing a pointer to a function, or a pointer in general to NULL helps some developers to make sure their pointer is uninitialized and not equal to a random value, thereby preventing them of dereferencing it by accident.

like image 135
Halim Qarroum Avatar answered Sep 25 '22 10:09

Halim Qarroum