'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.
Solution 1:[1]
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());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
