Search code examples
c++scopedynamic-arraysdynamic-allocation

Is memory freed when dynamic array goes out of scope


I am dynamically allocating memory for an array in a function. My question is: once the function finishes running is the memory freed?

code:

void f(){
    cv::Mat* arr = new cv::Mat[1];
    ...
}

Solution

  • No, it is not. You must free it by calling

    delete[] arr;
    

    But you should ask yourself whether it is necessary to allocate dynamically. This would require no explicit memory management:

    void f(){
        cv::Mat arr[1];
        ...
    }
    

    If you need a dynamically sized array, you could use an std::vector. The vector will internally allocate dynamically, but will take care of de-allocating it's resources:

    void f(){
        std::vector<cv::Mat> arr(n); // contains n cv::Mat objects
        ...
    }