Why don't I get SIGSEGV? [duplicate]

倖福魔咒の 提交于 2019-12-12 01:53:16

问题


I would like to understand what is going on here, more precisely why I do NOT receive a segmentation fault while writing on a memory location, which according to my understanding is not allocated.

Let's say I want to define a 2D array of int (testptr). One dimension (4) is allocated statically (as an "array"), the second dimension (2) dynamically (as a "pointer").

// First dimension 4 rows static
int *testptr[4];
for (i=0; i<4; i++)
    testptr[i] = calloc(2, sizeof(int));
// Second dimension 2 columns "dynamically" (in this example it is really just a constant)

Now I write to some locations:

testptr[0][0] = 5;
testptr[1][0] = 6;
testptr[2][1] = 7;
testptr[3][1] = 7;

All the above I expect to work fine, as they are within a 4x2 "array".

Now I write to a location which should not be allocated:

testptr[2][3] = 8;

And to make sure I write to many of them:

for (i=0; i<1000; i++)
    testptr[3][i] = i;

In none of these I get a segmentation fault nor other errors.

  1. Is it correct to say that we are writing on unallocated memory?
  2. Is it just luck that we are not receiving an error, as those unallocated memory locations are not reserved by other variables/processes?
  3. Can we assume that doing this will cause problems (segfaults) in other points of the programs?

Thanks for your answers.


回答1:


Your program invokes undefined behavior. It will give either expected or unexpected results. There is no guarantee that accessing arrays out of bounds will produce a segmentation fault or it will gonna crash your hard disk!



来源:https://stackoverflow.com/questions/27850221/why-dont-i-get-sigsegv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!