Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't dereferencing null crash my program?

I wrote the following code to induce a crash (I was testing out some issues with CrashReporter):

int *nullp = NULL;
int val = *nullp;    
NSLog(@"Hello world %d", val);

In a brand new project (I put it in the app delegate's applicationDidFinishLaunching:) it crashes as expected. But when I add it to one of my existing projects, it doesn't crash! In fact, it ends up printing "Hello world 0" to the system log.

This doesn't make any sense to me. Why doesn't the null dereference cause a crash?

like image 282
pepsi Avatar asked Dec 27 '22 01:12

pepsi


1 Answers

Dereferncing NULL has undefined behavior, it doesn't have to cause crash.

That being said, if you have different compiler options in the two project you have a good chance to get different behavior for those cases. See this LLVM blog post about undefined behaviors.

like image 128
MByD Avatar answered Jan 15 '23 01:01

MByD