Ceesz Ceesz - 2 months ago 6
C++ Question

Derefering NULL pointer c++

I get the warning: Derefering NULL pointer 'ch' on lines 2, 4

I don't understand why. Can someone help me out?

char *my_alloc(size_t size) {
char *ch = (char *)malloc(size);
//FIXED: If malloc fails -> exit program
if(*ch == NULL){
exit(0);
}
return ch;
}

Answer

if(ch == NULL) is what you need

you dereference ch at the code *ch inside if


ch == NULL check whether ch is NULL

*ch == NULL check whether the item point by ch is NULL