Skip to content

Instantly share code, notes, and snippets.

@boycgit
Created October 15, 2013 05:19
Show Gist options
  • Save boycgit/6986864 to your computer and use it in GitHub Desktop.
Save boycgit/6986864 to your computer and use it in GitHub Desktop.
内存泄露与迷途指针(C++)
#include <iostream>
using namespace std;
int main(){
int *p = new int; //在堆里创建指针
*p = 10; //将值赋给指针所指向的地址
cout<<"*p="<<*p<<endl;
// delete p;
p = new int; //内存泄露:没有释放之前的内存
*p = 20; //new之前先delete
cout<<"*p="<<*p<<endl;
delete p;
//p = 0;
*p = 300; //delete p后,没经过p = 0;所以成为迷途指针
//现在可能有其他数据存储在这个地方
cout<<"*p="<<*p<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment