EXC_BAD_ACCESS (code=1, address=0x10) when implement logic operation to NULL pointer

Hello. I'm just studying C programming, and I have a trouble with impossibility to implement logic operation to pointer with NULL value. For example:

int * ptr; ptr = NULL: if (ptr) { printf("Ptr isn't NULL\n"); } else { printf("Ptr is NULL\n"); }

I get exception = EXC_BAD_ACCESS (code=1, address=0x10).

The real case in lldb debugger in picture.

Please, help me. This issue really breaks programming principles which I must learn.

Your logic is, in general, fine. In C a pointer is either NULL or it isn’t, and this code can distinguish between those cases:

int * ptr = … something …
if (ptr) {
    … pointer is not NULL …
} else {
    … pointer is NULL …
}

The real case in lldb debugger in picture.

It’s hard to say what’s going on here without looking at the assembly code that the compiler generated [1]. I suspect that tmp_rec is not NULL but it’s also not a valid pointer. For example, if tmp_rec were 0x04 and the offset of next in las_rec were 0x0c then you’d crash like this.

If you update your print statement on line 174 to print the pointer values, what do you see?

Note that the correct format modifier for a pointer is %p.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] One of the pitfalls of C-based languages is that their overwhelming use of pointers makes that any tiny mistake leaves you debugging at the assembly level.

EXC_BAD_ACCESS (code=1, address=0x10) when implement logic operation to NULL pointer
 
 
Q