内存泄露与野指针的思考

来源:互联网 发布:linux windows 性能 编辑:程序博客网 时间:2024/04/29 21:37

数据大小与指针大小?

int a=sizeof(char);//a的值为1.int b=sizeof(char*);//b的值随编译器和操作系统改变。在win32系统,应该是4.32位寻址---即4Byte。

不应妄自揣度内存大小

struct MyStruct{long dwNumber;int  nsize;long  dwId;};//long takes 4byte//int takes 2byteMyStruct *  pstruct;Pstruct=(MyStruct*)malloc(???);//由于内存对齐的影响,结构体类型的内存块不能够“目测”计算,特别是不能使用strcpy。这是绝对错误的。
内存泄露

void GetBuffer(void){char *pstr;pstr = (char*)malloc(sizeof(char)*10);}//malloc之后需要确保free。只分配一次内存的全局对象不free的话,按道理是影响不大的,进程在结束的时候会清理这些内存。未曾尝试。请勿模仿
内存生命周期与变量生命周期比较 

void GetBuffer(void){char *pstr;pstr = malloc(sizeof(char)*1024);}void Printline(void){int ncount=1;char* pstr;}void main(){GetBuffer();Printline();}//此段代码需要自己慢慢品味。
野指针

char *pstr=null;pstr=(char*)malloc(sizeof(char)*1024);//..free(pstr);if(pstr!=null){printf(“%s”,pstr);}//任何free内存块的操作之后都应该接一个指针置空操作。否则可能访问野指针。
常见野指针 

char *pstr=null;Pstr=(char*)malloc(sizeof(char)*1024);//..free(pstr);Pstr=null;//所有free都应该与之相随if(pstr!=null){printf(“%s”,pstr);}
同理new与delete

class HttpPostGet{//..};HttpPostGet *phttppostget=null;Phttppostget=new HttpPostGet();//..delete phttppostget;Phttppostget=null;//应该相随相伴。
最错误的代码

void GetBuf(char *pstr){pstr=malloc(sizeof(char)*1024);}main(){char *pstr;GetBuf(pstr);char *psource=“abc”;strcpy(pstr,psource);}//兼具内存泄露与野指针。

和如下代码段有何区别?

<pre name="code" class="cpp">void funcB(char * p){     char * temp="temp";     p=(char*)malloc(sizeof(char)*1024);     strcpy(p,temp);}void main(int argc,char ** argv){     char * mypoint=NULL;     funcB(mypoint);     pirntf("func b is %s",mypoint);}

和如下代码段有何区别?

void funcA(char * p){     char * temp="temp";     strcpy(p,temp);}void main(int argc,char ** argv){     char * mypoint=NULL;     mypoint=(char*)malloc(sizeof(char)*1024);     if(mypoint!=NULL)            funcA(mypoint);     pirntf("func a is %s",mypoint);






为何有malloc free还要有new delete?


C语言内存管理参考书


0 0
原创粉丝点击