my code in c++. Will there be a memory leak?

Viewed 91
int * myArr(int num) {
    static int *Arr = new int[num];
    for (int i{ 0 }; i < num; i++) {
        *(Arr + i) = i;
        std::cout << *(Arr + i) << "\n";
    }
    //delete[] Arr;
    return Arr;
}

int main()
{
    int *testArr = myArr(4);
    for (int i{ 0 }; i < 4; i++) {
        std::cout << *(testArr + i) << "\n";
    }
    delete[] testArr;
}

is there a memory leak if i try to delete[] testArr inside main() instead of delete[] Arr in the myArr function? Thanks for your reply.

1 Answers

Will there be a memory leak?

There is no leak in the example.

if i try to delete[] testArr inside main() instead of delete[] Arr in the myArr function?

If you did that, then attempting to access the array in main would result in undefined behaviour. Don't do that.


P.S. Don't use bare owning pointers. Use std::vector instead. Example:

std::vector<int> myArr(int num) {
    auto iota = std::ranges::iota_view{0, num};
    return std::vector<int>(iota.begin(), iota.end());
}
Related