some_user
some_user

Reputation: 179

dynamic 2d-array - missing segmentation fault?

I have the following code:

int **a = new int*[n+1];
for(int i = 0; i <= n; i++) a[i] = new int[1];

Now - to my understanding - the first statement allocates memory for n+1 int pointers, in the loop, for each of these int pointers there 1 * sizeof(int) memory is allocated (a[i] is pointer to the first int).

If I output the array in 2 i = 0 to n loops, it doesn't give a segmentation fault:

    for(int i = 0; i <= n; i++) {
      for(int j = 0; j <= n; j++)
         printf("%d ",a[i][j]);
      printf("\n");
   }

Why can I access a[i][j] where j > 0, as I only allocated memory for one int, without getting a Segmentation fault?

Upvotes: 1

Views: 177

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598289

Your code has undefined behavior.

When creating the arrays, your loop allocates an int[1] array for each int* pointer in the outer array. That is OK.

When accessing the arrays later, accessing the int* pointers via a[i] is fine since i does not go out of bounds of the a[] array. But [j] does go out of bounds as 0 is the only index that is valid to access an element of an int[1] array.

Undefined behavior does not guarantee that a segfault will occur. In this case, the lack of a segfault simply means that the memory addresses you are accessing through invalid indexes just happen to be valid within the address space of your program, but they are not valid within the bounds of the arrays. So you end up printing out random garbage from surrounding memory.

Upvotes: 4

Related Questions