我只是想知道如何使用C ++创建系统内存泄漏。我已经对此进行了一些谷歌搜索,但没有多少提出来,我知道在C#中实现它并不是真的可行,因为它是托管代码但是想知道是否有一种简单的方法可以用C ++做到这一点?我只是觉得有趣的是看到系统因为代码编写不当而遭受多少损失。感谢。
答案 0 :(得分:25)
如果您稍后调用new
而未调用相应的delete
,则会发生内存泄漏。如示例代码所示:
int main() {
// OK
int * p = new int;
delete p;
// Memory leak
int * q = new int;
// no delete
}
答案 1 :(得分:24)
答案 2 :(得分:12)
int main() {
while(true) new int;
}
答案 3 :(得分:7)
内存泄漏的种类很多:
分配的内存无法释放,因为没有任何内容指向它 在C和C ++中很容易创建这种泄漏。它们也很容易预防,易于检测,易于治愈。因为它们易于检测,所以有许多工具,免费和商业,以帮助发现这种泄漏。
应该在很久以前发布的仍然可以访问的分配内存
这些类型的泄漏更难以检测,预防或治愈。还有一些东西指向它,它最终将被发布 - 例如,在exit()
之前。从技术上讲,这不是一个泄漏,但出于所有实际目的,这是一个泄漏。许多据称无泄漏的应用程序都有这样的泄漏。您所要做的就是运行系统配置文件,以查看一些愚蠢的应用程序消耗更多的内存。即使在托管语言中,这些类型的泄漏也很容易创建。
首先应该永远不会分配的分配内存
示例:用户可以轻松地要求Matlab创建这些类型的泄漏。 Matlab在创建这类泄漏方面也非常积极。当Matlab从malloc
收到故障时,它会进入一个等待一段时间的循环,然后重试malloc
。同时,操作系统疯狂地尝试通过将程序块从实内存中移入虚拟内存来处理内存丢失。最终一切都在虚拟内存中 - 一切都悄然停滞。
答案 4 :(得分:5)
我发现这篇文章对stress testing很有用 - 它也带有代码示例。
答案 5 :(得分:3)
只需编写一个分配“大量数据”的应用程序,然后阻塞直到它被杀死。只需运行此程序并使其保持运行。
答案 6 :(得分:2)
在C#中,只需使用P / Invoke分配大量内存,资源句柄并保留它们。
您可以在简单的C#harness中使用非托管代码
答案 7 :(得分:2)
class ClassWithLeakedMemory{
private:
char* str;
public:
ClassWithLeakedMemory(){
str = new char[100];
}
~ClassWithLeakedMemory(){
cout<<"We are not freeing the dynamically allocated string memory"<<endl;
}
};
class ClassWithNoLeakedMemory{
private:
char* str;
public:
ClassWithNoLeakedMemory(){
str = new char[100];
}
~ClassWithNoLeakedMemory(){
cout<<"We are freeing the dynamically allocated string memory"<<endl;
delete[] str;
str = null;
}
};
int main() {
//we are creating an automatic object of the ClassWithleakedMemory
//when we will come out of the main, this object will be
//out of scope. hence it will be deleted. so destructor will
//be called. but in the destructor, we have not specifically
//deleted the dynamically allocated string.
//so the stack based pointer object str will be deleted but the memory
//it was pointing to won't be deleted. so we will be left with an
//unreferenced memory. that is memory leak.
ClassWithLeakedMemory objectWithLeakedmemory;
ClassWithNoLeakedMemory objectWithNoLeakedmemory;
return 0;
}
基于堆栈的指针对象引用两个类中动态分配的内存的方式可以如下图所示:
答案 8 :(得分:1)
就这么简单:⠀⠀⠀
new int;
答案 9 :(得分:0)
#include <stdio.h>
void main(){
for(int i = 0; i < 1000; i++)
double* ptr = (double*)malloc(1000000*sizeof(double))
//free(ptr);
ptr = NULL;
}
注意:散列的代码行导致内存泄漏,而进程分配它并且没有将其返回给操作系统
答案 10 :(得分:0)
当不再引用使用new
创建的对象时,必须将delete
运算符应用于该对象。如果没有,它将占用的内存将丢失,直到程序终止。这称为内存泄漏。这是一个例子:
#include <vector>
using namespace std;
void memory_leak(int nbr)
{
vector<int> *ptrVector = new vector<int>(nbr);
// some other stuff ...
return;
}
如果我们返回时未在对象(即delete
)上调用delete ptrToVector
,则会发生内存泄漏。为了避免这种情况,请不要在内存堆上分配本地对象,而应使用堆栈分配的变量,因为这些变量会在函数退出时自动清除。要在运行时堆栈上分配向量,请避免使用new
(在堆上创建向量)和指针。