pen*_*926 0 c++ memory-management
我遇到了这个我今天无法解释的问题.
int main(){
vector<int> vec = subroutine();
...
delete(&vec);
}
vector<int>& subroutine(){
vector<int>* vec = new vector<int>();
//Init the vec
for(int i=0;i<vec.size();i++){
...
}
return *vec;
}
Run Code Online (Sandbox Code Playgroud)
它出现了一个错误:
double free or corruption (out): 0X00007fffa145ff50
Run Code Online (Sandbox Code Playgroud)
这绝对是该行的问题:
delete(&vec);
Run Code Online (Sandbox Code Playgroud)
但我无法解释,为什么有双免费?
jua*_*nza 10
您正在调用delete未分配的内容,new因为您正在复制新创建的矢量.您可以通过不复制向量来"纠正"您的代码:
vector<int>& vec = subroutine();
Run Code Online (Sandbox Code Playgroud)
但这种功能真的是在惹麻烦.解决这个问题的正确方法是按值返回向量.
vector<int> subroutine() {
vector<int> vec;
//Init the vec
for(int i=0;i<vec.size();i++){
...
}
return vec;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |