Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my program seg fault when I dereference a NULL pointer inside of malloc?

I use this malloc style all the time

int *rc = 0;
rc = malloc(sizeof(*rc));

However, it doesn't seg fault even though when I call sizeof(*rc) I assume that rc==0, and I am dereferencing a NULL pointer.

like image 587
CallMeNorm Avatar asked Nov 26 '12 22:11

CallMeNorm


People also ask

Does dereferencing a null pointer cause segmentation fault?

If the program dereferences the null pointer, it can cause a segmentation fault or other undefined behavior, which can lead to a crash.

What is the problem with dereferencing the null pointer?

Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.

Can malloc seg fault?

It is usually the next-block pointer inside the malloc that is changed by your heap corruption to an invalid address, so that when you call malloc an invalid pointer gets dereferenced and you get a segmentation fault.

How to cause a seg fault?

In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).


2 Answers

You are not really dereferencing anything. The argument of sizeof is not evaluated, unless it is a VLA. It is explicitly allowed by the language to put whatever "garbage" you want as the argument of sizeof. The language guarantees that it will not evaluate anything, just perform compile-time analysis of the type of the expression. For example, expression sizeof i++ is guaranteed not to change the value of i.

The only exception from that rule is Variable Length Arrays. The result of sizeof for VLAs is a run-time value, which means that the argument is evaluated and must be valid.

like image 104
AnT Avatar answered Oct 16 '22 13:10

AnT


The sizeof operator doesn't actually evaluate its operand, it only looks at its type. The type of *rc is int, so it's equivalent to sizeof (int). This all happens at compile time.

(Also, this is not "inside of malloc".)

like image 24
melpomene Avatar answered Oct 16 '22 13:10

melpomene