int ** foo()
{
int ** multiArray = new int*[3];
int one[3] = { 1, 2, 3 };
int two[3] = { 4, 5, 6 };
int three[3] = { 7, 8, 9 };
multiArray[0] = one;
multiArray[1] = two;
multiArray[2] = three;
return multiArray;
}
Returning multiArray works outside of the above function, but I have reserves about the the way the inner arrows (one, two, three) are allocated. My first reaction is that they are allocated on the stack, not the heap. I would want the heap. Even though they somehow work for me outside of that function, when I try to delete them as I should, it fails.
If I do something such as:
int ** allocatedMultiArray = foo();
int test = allocatedMultiArray[0][2]; // We get 3! Success!
for (int i = 0; i < 8; ++i)
{
delete[] allocatedMultiArray[i]; // FAILS!
}
delete[] allocatedMultiArray; // WORKS! (If we skip the above for loop of course)
I was reading this page on multi-dimensional array and he specifically had to the above for loop to deallocate a 2D array (or an additional loop for a 3D array). But, back in my equivalent of foo(), he manually allocated the array to the heap with the new operator with a loop as opposed to { 1, 2, 3 } initializing an array then assigning it like I did. http://www.cplusplus.com/forum/articles/7459/
So if I skip the for loop that fails, am I leaking memory? Is what I am doing should even work? I really don't want to loop over the multiArray, call new on each index, then manually assign each int. This is just a simplified { 1, 2, 3 } but I have a somewhat more complex number set obtained from different functions that reads much better with the { } notation.
EDIT: The failure on that inner delete is:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
EDIT2: So if it is undefined behavior and the one, two, three arrays are not allocated on the heap as I initially believed, then how does one do something like the following:
int ** foo()
{
int ** multiArray = new int*[3];
for(int i = 0; i < 3; ++i)
{
multiArray[i] = new int[3];
}
multiArray[0] = { 1, 2, 3 }; // Fail "Too many initializer values" on 2
multiArray[1] = { 4, 5, 6 }; // Fail
multiArray[2] = { 7, 8, 9 }; // Fail
return multiArray;
}
EDIT 3: Not a duplicate as I was specifically asking for a different answer than the ones provided on the question, as well as the fact that I was trying to identify if the arrays were being done on the heap or stack. Neither of which are addressed in the question marked as a duplicate. In fact, I specifically addressed the most upvoted answer of that question saying that it was insufficient.