jeudi 8 janvier 2015

Why don't I get SIGSEGV?


Vote count:

0




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(sizeof(int), 2);
// 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.



asked 31 secs ago







Why don't I get SIGSEGV?

Aucun commentaire:

Enregistrer un commentaire