小编Joh*_*hnZ的帖子

使用动态内存来避免引用失效

#include <iostream>
#include <vector>
#include <cstring>

using namespace std; //please ignore bad practices like this and everything being set to public. Its just for sake of demonstration.

vector<int>& f() {
    vector<int> a = *new vector<int>{15, 15, 16};
    return a;
}

int main () {
    vector<int>& b = f();
    
    for (auto x: b) {
        cout << x << endl;
    }
delete &b;
    
    cout << "finished" << endl;
}
Run Code Online (Sandbox Code Playgroud)

你好:

在上面的代码中,我使用动态分配的内存,以便向量 a 将其内存存储在堆上,这样就可以避免在函数退出后被删除。但由于某种原因,它没有。该代码给了我这个无法理解的错误:

=================================================================
==22==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000030 at pc …
Run Code Online (Sandbox Code Playgroud)

c++ memory-management reference

1
推荐指数
1
解决办法
142
查看次数

标签 统计

c++ ×1

memory-management ×1

reference ×1