几个小例子--memory leak

来源:互联网 发布:qq图标点亮软件 编辑:程序博客网 时间:2024/05/09 03:05

C++程序员最害怕、最容易遇到的问题就是内存泄露,或是说非法访问内存。

不想说太多的道理,就用几个简单的例子来诠释。

指针超过作用域

void MemoryLeak( ){  int *data = new int;  *data = 15;}

在释放前产生异常

void MemoryLeak() {    int* ptr = new int;    // do something which may throw an exception    // we never get here if an exception is thrown    delete ptr;}

没释放就赋值nullptr

int * a = malloc(sizeof(int)); a = 0; //this will cause a memory leak

new/delete new[]/delete[] malloc/free没有成对出现、没有匹配

char *s = (char*) malloc(5); delete s;   //不能使用delete去释放malloc分配的内存

释放两次,没有赋为nullptr

char* pStr = (char*) malloc(20); free(pStr); free(pStr); // results in an invalid deallocation

返回局域变量的指针

MyClass* MemoryLeak(){  MyClass temp;  return &temp;}

使用已经释放的指针

...delete ptr;ptr = nullptr;ptr->show();

不要delete形参的指针

char* function( char* c){  char* temp = new char [ strlen (c) + 1 ];  strcpy ( temp, c );  delete[] c; //错误,不应该删除形参的指针  return temp;//错误,返回局域变量的指针}

使用了没有分配内存的指针

MyWindow* window;window->show();

delete非heap上的内存

MyWindow window;delete window;
2 0
原创粉丝点击