内存分配不成功导致内存泄漏的问题

来源:互联网 发布:秀萝捏脸数据 编辑:程序博客网 时间:2024/06/06 04:26

内存泄漏是在写程序中容易发生的问题,所以解决内存泄漏问题至关重要,在这里我推荐一个内存泄漏的自动化检测软件:visual leak detector,非常好用的一个软件


#include <iostream>

void GetMemory(char  *p, int num)

{

p = (char *)malloc(sizeof(char) * num);

}

int main()

{

char  *str = NULL;

GetMemory(str, 100);

strcpy(str, "hello");

return 0;

}

上述代码 p申请了新的内存,但是p只是str的一个副本(编译器为函数参数制作临时副本),p指向的内存地址改变了,而str却没有改变。GetMemory没有返回值, 申请的内存得不到释放,最终造成内存泄漏。


解决方法1:采用指向指针的指针,传str的地址给函数

#include <iostream>

void GetMemory(char  **p, int num)

{

*p = (char *)malloc(sizeof(char) * num);

}

int main()

{

char  *str = NULL;

GetMemory(&str, 100);

strcpy(str, "hello");

return 0;

}

方法2:加返回值

#include <iostream>

char *GetMemory(char *p, int num)

{

p = (char *)malloc(sizeof(char) * num);

return p;

}

int main()

{

char  *str = NULL;

str = GetMemory(str, 100);

strcpy(str, "hello");

return 0;

}



0 0
原创粉丝点击