简体   繁体   中英

NULL pointer comparison to zero segfaults

So, I have this piece of C code:

226     if (!pair)
227         return;
228     if (!pair->index)
229         free(pair->index);

I am running through it with a non-null 'pair' pointer which has a null (0) member 'index'. It works wonderfully, as one might expect. On the other hand, this

226     if (!pair)
227         return;
228     if (pair->index!=NULL)
229         free(pair->index);

generates a segmentation fault (on line 228, where the if is). It seems weird, since the two should be identical, right? (the second makes even more sense to me than the first, that's why I used it in the first place)

I am fine with just using the negative expression which works, but I want to understand why the second segfaults. Any ideas? :)

(I am building with gcc (Debian 4.7.2-5) 4.7.2 )

Thanks!

First thing to note, standard c already has the null check built into free so you ought not to check this again yourself.

In your first snippet, the line if (!pair->index) free(pair->index); is benign probably due to a typo: free is only called if the pair->index is null, and free will pass over that as I've already said. You have an errant ! in your if statement. So your program is unlikely to crash there. (Technically it might if pair->index is uninitialised since the use of an uninitialised variable is undefined behaviour in c).

There is no problem in the second snippet you present, unless pair->index is not pointing to memory given to you by a prior call to malloc , calloc etc. If you are sure you own the memory at pair->index then the problem is due to a heap corruption or an undefined behaviour construct elsewhere in your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM