Pointer of array never seg fault?

633 views c++
4

I have something I don't understand.

Here is what I do :

float* test = (float*) malloc(4 * sizeof(float) );

And then I tried to do

test[100] = 1.0;
printf("%f\n",test[100]);

And ... It worked...

I was waiting for a segmentation fault, but no and I don't understand why. I wanted to do this to verify that my array has been correctly allocated. I really didn't expected that, and maybe I miss something so I searched on the internet, and it seems that everybody get a segfault ... So I came here to ask. Thanks

answered question

What you do causes undefined behavior, including sometimes not segfaulting...

To begin with please pick the language you actually program in. C and C++ are two very different languages. Secondly, please read about how to ask good questions, as well as this question checklist. And of course please try to create a Minimal, Complete, and Verifiable Example to show us. Then edit your question to improve it, like for example tell us why you expected a crash.

This question is relevant to both C and C++ though, isn't it?

As another point of improvement, it's not clear how your pointer test from the first snippet fits together with your array test in the second. A MCVE will help us understand that better.

1 Answer

8

What you caused is undefined behavior - in this case, it works as expected, but it's a terrible idea to rely on it in any way: compiler optimizations or changing the operating system might suddenly cause "weird" behavior. You should read more on this topic, though in a nutshell, with undefined behavior, the compiler is allowed to do whatever it wants.

I don't have enough knowledge to be sure, but I hypothesize that your Operating System prepared a whole memory page for your program. In Linux by default it is 4 KiB, and you accessed bytes up to 400, so there is still plenty of room. Thus, you might be accessing memory that is allocated for your program, as the operating system works with memory blocks not smaller than 4 KiB.

posted this

Have an answer?

JD

Please login first before posting an answer.