1

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?

4
  • Your code invokes undefined behavior. You're seek definition where there is none. There is no guarantee that your program will fault, or for that matter, even fail. but I can assure you; it will choose a time and a place most-inopportune to do so. While it may appear to function in your test jig, perhaps running on your professor's rig, or worse, a paying customer environment, will reap the (unfortunate) behavior you are expecting here. Commented Aug 3, 2020 at 21:54
  • The key is Undefined Behavior does not mean crash. Commented Aug 3, 2020 at 21:55
  • @drescherjm That's what I'm doing, I just wondered why the above code was working without a segmentation fault, but it seems I just had seg-fault and undefined behaviour confused :) Commented Aug 3, 2020 at 21:56
  • 2
    One of the worst behaviors of undefined behavior is when the program appears to work even though it is broken. You have found one such case on your environment. Commented Aug 3, 2020 at 21:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.