Search code examples
c++arrayspointersdynamic-memory-allocation

How do I allocate a 3D array in C++ on the free store?


I am currently learning how to utilize raw pointers in C++. I understand how to dynamically allocate a 2D array, however, as an exercise for myself, I attempted to apply my understanding of multiple levels of indirection to allocate a 3D array. My attempt is presented below:

int main() {

    double*** matrix { new double**[10] {} };

    for (size_t i {}; i < 10; ++i) {

        matrix[i] = new double*[i + 1] {};

        for(size_t j {}; j < 10; ++j) {

            matrix[i][j] = new double[i + 1] {};
        }

    }

    std::cout << matrix[0][0][0] << std::endl;

    for (size_t i {}; i < 10; ++i) {

        for (size_t j {}; j < 10; ++j) {
            delete[] matrix[i][j];
            matrix[i][j] = nullptr;
        }

        delete[] matrix[i];
        matrix[i] = nullptr;

    }

    delete[] matrix;
    matrix = nullptr;

    return 0;

}

Since I'm using uniform initialization, matrix[0][0][0] should print the value 0.0; However, I'm getting a garbage value when doing so. Furthermore, I have a double free or corruption (out) error, which I assume is telling me that I am attempting to free memory from the same address twice.

Any help or guidance would be appreciated. I'm just trying to fully understand raw pointers.

Edit: I understand that double*** is not actually a 3D array. I'm just trying to utilize simple terminology.


Solution

  • matrix[i] = new double*[i + 1] {};
    for(size_t j {}; j < 10; ++j) {
    

    This is your error right here, you allocate an array of 'i + 1' element and then loop for 10, you either need to have i + 1 in both places or 10 otherwise this is undefined behavior. The same applies for deletion (the loop checks for 10 but you only allocated i + 1).