I have a function that can return a pointer to a structure or NULL (Example to explain return possibilities of get_my_struct_from_[X] functions):
struct my_struct *my_function(my_struct i) {
if (i.value < 5) return i;
else return NULL;
}
In the main program I'm calling this function multiple times and then checking if the value is NULL or not:
struct my_struct *q;
q = get_my_struct_from_A();
if (q == NULL) {
// display an error message and exit
}
q = get_my_struct_from_B();
if (q == NULL) {
// display an error message and exit
}
CppCheck is telling me that the if statements are redundant or there is a possible null pointer dereference.
Questions:
- Why does CppCheck gives me these messages?
- How to correctly check the return value of the function so I don't get this message
EDIT:
Forgot to mention that the my_function is an example for how the two get functions behave.
The get_my_struct_from_A and get_my_struct_from_B have different internal logic, but the output data types are the same as show in my_function. I have a lot of get_my_struct_from_X functions that I call and check the return values. So creating a new structure for each get is not an option, I don't consider that a good, because of the large amount of variables used for the same purpose.
Writing q == null
or !q
returns the same messages from cppcheck which is normal I think.