| ▲ | jmalicki a day ago | |||||||||||||||||||||||||||||||||||||||||||
A lot of compilers will optimize out a NULL pointer check because dereferencing a NULL pointer is UB. Because assert will not run the following code in the case of a NULL pointer, AFAIK this exact code is still defined behavior, but if for some reason some code dereferenced the NULL pointer before, it would be optimized out - there are some corner cases that aren't obvious on the surface. This kind of thing was always theoretically allowed, but really started to become insidious within the past 5-10 years. It's probably one of the more surprising UB things that bites people in the field. GCC has a flag "-fno-delete-null-pointer-checks" to specifically turn off this behavior. https://qinsb.blogspot.com/2018/03/ub-will-delete-your-null-... This is an actual Linux kernel exploit caused by this behavior where the compiler optimized out code that checked for a NULL pointer and returned an error. | ||||||||||||||||||||||||||||||||||||||||||||
| ▲ | IshKebab a day ago | parent [-] | |||||||||||||||||||||||||||||||||||||||||||
Sure, but none of that is relevant to just the code snippet that was posted. The compiler can exploit UB in other code to do weird things, but that's just C being C. There's nothing unexpected in the snippet posted. The issue is cause by C declaring that dereferencing a null pointer is UB. It's not really an issue with assertions. You can get the same optimisation-removes-code for any UB. | ||||||||||||||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||||||||||||||