如何释放函数中分配的内存而不返回其指针?

How to free memory allocated in a function without returning its pointer?

我有这样的功能:

int fun(){
    int* arr = new int[10];
    for(int i = 0; i < 10; i++){
        arr[i] = 5;
    }
    delete[] arr;  // 
    return arr[6];
}

int main(){
    std::cout << fun();
    return 0;
} 

我要做的是释放指针 arr 指向的内存。但是函数没有返回指针 arr。所以我试着在函数中释放它。
如果 delete[] arr 高于 return arr[6](使用 Visual Studio 2019),它不会打印任何内容。
但是如果return arr[6]delete[] arr之上,是不是释放内存还是跳过这句话?
或者我应该在 main() 中声明 arr 然后在 main() 中释放它?

除非是出于学术目的,否则你很少看到C++程序使用手动内存分配,你不需要这样做,因为你有一组容器在STL containers library that do this memory management reliably for you. In your particular example, a std::vector推荐。

也就是说,回答你的问题:

It won't print anything if delete[] arr is above return arr[6] (Using Visual Studio 2019).

如果在访问数组中存储的数据之前删除数组,则行为未定义。它不打印任何东西是很自然的。 It could also print the expected result, that's one of the features of undefined behavior。用不用Visual Studio都是一样的

But if return arr[6] is above delete[] arr, would the memory be freed or this sentence be skipped?

是的,它会被跳过,或者更准确地说,return语句之后的所有代码都不会被执行。内存不会被释放。

Or should I declare arr inside main() then free it in main()?

如果数据应该属于 main 的范围,你绝对应该在那里声明它,你可以将它作为参数传递给函数:

#include <cassert>
#include <iostream>

int fun(int* arr) {
    assert(arr);
    for (int i = 0; i < 10; i++) {
        arr[i] = 5;
    }
    return arr[6];
}

int main() {
    int* arr = new int[10];
    std::cout << fun(arr);
    delete[] arr;
    return 0;
}