4

I have the following code:

int **arr = new int*[5];

for(int i = 0; i < 5; ++i)
    arr[i] = new int[];

for(int i = 0; i < 5; ++i)
    delete [] arr[i];

delete [] arr;

Now it compiles and runs successfully, however if I remove the array size '5' from the first line the code compiles but crashes with run-time error on the last line. I have the following questions that I have failed to find answers in Straustrup's C++ book, in the internet etc.

  1. Why the code crashes in the specified case ? (My guess is that delete [] fails to find the array size to be deleted and crashes.)
  2. If it is not allowed to allocate multidimensional arrays without indicating the size why such errors are not caught by compiler at compile time ?
3

1 Answer 1

3

With the [5], you're getting an array of 5 int*s.

If you remove the [5], you're saying you want a pointer to a pointer to an int. So essentially, you have new int*[1].

Then you are indexing it with numbers from 0 to 4, which is out of bounds.

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

1 Comment

Seth Do you mean that int*[] is equivalent to int*[1] ? If so then the code should crash inside the first "for" loop during second iteration, however in fact it crashes on the last line.

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.