Tuan Pham
Tuan Pham

Reputation: 21

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

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.

Upvotes: 2

Views: 97

Answers (1)

eerorika
eerorika

Reputation: 238281

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());
}

Upvotes: 2

Related Questions