Struct c++中的内存泄漏
Memory Leak in Struct C++
我有一个这样的结构,
struct int * ramp_output (int * L10)
{
int * r;
r = L10;
return(r);
}
我应该从L10和r中释放内存吗?
首先,您的代码将无法在那里编译多余的"struct"。删除它,我们可以回答你的问题:这取决于参数是如何分配的,但在任何情况下你都应该只做一次。
int main()
{
int a[] = { 1, 1, 1 };
int i = 42;
int* pi1 = &i;
int* pi2 = new int[10];
int* pi3 = new int(42);
std::vector<int> v( 10 );
std::shared_ptr<int> sp( new int(42) );
int* r1 = ramp_output(a);
int* r2 = ramp_output(&i);
int* r3 = ramp_output(pi1);
int* r4 = ramp_output(pi2);
int* r5 = ramp_output(pi3);
int* r6 = ramp_output(&v[0]);
int* r7 = ramp_output(sp.get());
// what to dealloc? Only these
delete [] pi2; // or delete [] r4; but not both!
delete pi3; // or delete r5; but not both!
}
结构体不接受参数或返回值。如果你从代码中删除"struct",这将是一个有效的(尽管微不足道)函数:它只是返回一个指针,指向它的参数是一个指针。您不需要或不想释放任何内存
作为一般规则,在c++中唯一需要释放内存的时候是使用"new"关键字创建内存的时候。例如
int * test = new int;
在这种情况下,指针"test"指向堆上的一个整数,"某人"应该删除它。谁负责删除它取决于你的程序设计,如果你把指针传递给其他函数,而它们存储/使用它的副本,你不应该删除它。
至于你的示例代码,它真的没有任何意义,所以你必须告诉我们你到底想做什么来帮助解决这个问题。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏