c - NULL pointer comparison to zero segfaults -
so, have piece of c code:
226 if (!pair) 227 return; 228 if (!pair->index) 229 free(pair->index);
i running through non-null 'pair' pointer has null (0) member 'index'. works wonderfully, 1 might expect. on other hand, this
226 if (!pair) 227 return; 228 if (pair->index!=null) 229 free(pair->index);
generates segmentation fault (on line 228, if is). seems weird, since 2 should identical, right? (the second makes more sense me first, that's why used in first place)
i fine using negative expression works, want understand why second segfaults. ideas? :)
(i building gcc (debian 4.7.2-5) 4.7.2 )
thanks!
first thing note, standard c has null check built free
ought not check again yourself.
in first snippet, line if (!pair->index) free(pair->index);
benign due typo: free
called if pair->index
null, , free
pass on i've said. have errant !
in if
statement. program unlikely crash there. (technically might if pair->index
uninitialised since use of uninitialised variable undefined behaviour in c).
there no problem in second snippet present, unless pair->index
not pointing memory given prior call malloc
, calloc
etc. if sure own memory @ pair->index
problem due heap corruption or undefined behaviour construct elsewhere in program.
Comments
Post a Comment