Access NULL pointer

T

Tagore

Hi,

I was trying to debug a project.
I found that pointer to one of struct record was NULL, but it was
still able to dereference and take some garbage value.
i.e. if foo is a pointer whose value is NULL. then when I try to
access a data member like foo->bar..it is still able to take some
garbage value of bar despite foo being NULL.
How is it possible? Should not it crash here?

Thanks,
 
I

Ian Collins

Hi,

I was trying to debug a project.
I found that pointer to one of struct record was NULL, but it was
still able to dereference and take some garbage value.
i.e. if foo is a pointer whose value is NULL. then when I try to
access a data member like foo->bar..it is still able to take some
garbage value of bar despite foo being NULL.
How is it possible? Should not it crash here?

It depends. That's the joy of undefined behaviour.

If the address offsetof( record, bar ) is valid, it might not crash.
 
P

Peter Nilsson

Tagore said:
I was trying to debug a project.
I found that pointer to one of struct record was NULL,
but it was still able to dereference and take some
garbage value. i.e. if foo is a pointer whose value is
NULL. then when I try to access a data member like
foo->bar..it is still able to take some garbage value
of bar despite foo being NULL.
How is it possible? Should not it crash here?

Did you miss the thread titled 'C Standard Regarding Null
Pointer Dereferencing'?

Undefined behaviour means *anything* can happen, including
the illusion that everything works just fine.
 
A

Andrey Tarasevich

Tagore said:
How is it possible? Should not it crash here?

There's no such thing as "crash" in C language. What it has instead is
called "undefined behavior". Undefined behavior can manifest itself in
many different ways, none of which is better that the others. The
program might "crash", or the program might return a "garbage value". As
far as the language is concerned, there's no difference between
"crashing" and "returning garbage".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top