- 论坛徽章:
- 1
|
本帖最后由 hanzhenlll 于 2012-10-13 12:42 编辑
pmerofc 发表于 2012-10-13 12:23 ![]()
回复 7# hanzhenlll 28. getmem (p2);
这个是缘木求鱼
28. getmem (p2);
这个是缘木求鱼
p2的值可以传给getmem(),但你不能指望通过调用getmem()改变p2的值
point生命期结束
而point是那块内存位置的唯一的记录
所以,调用结束后,那块内存你就再也找不着了。这就是内存泄漏
嗯, 谢谢....我上面的代码就是验证这个问题的,以前我没注意过,一直有误解,所以这次搞明白了... &p2就可以了吧...传内存地址本身,在这个基础上malloc 就可以修改p2的值了,没错吧?
缘木求鱼查了查意思 好形象啊... point内存的问题,按照如上方法使用后,main使用完毕后free也是能够保障内存无泄漏的吧? 感谢指正- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void getmem (char **point)
- {
- printf ("Getmem point 0x%x, 0x%x\n", *point, point);
- if ((*point = (char *)malloc (100)) == NULL)
- {
- printf ("malloc error !\n");
- // free NULL return
- }
- printf ("Getmem point 0x%x, 0x%x\n", *point, point);
- }
- int main (int argc, char *argv[])
- {
- char *p1 = NULL, *p2 = NULL;
- printf ("Init: p1 = 0x%x, 0x%x, p2 = 0x%x, 0x%x\n", p1, &p1, p2, &p2);
- p1 = (char *)malloc (100);
- printf ("Malloc: p1 = 0x%x, 0x%x\n", p1, &p1);
- strcpy (p1, "world");
- printf ("strcpy world --->%s \n", p1);
- getmem (&p2);
- printf ("After p2 = 0x%x, 0x%x\n", p2, &p2);
- strcpy (p2, "hello");
- printf ("%s \n", p2);
- // free NULL
- return 0;
- }
复制代码 Init: p1 = 0x0, 0xbf99f948, p2 = 0x0, 0xbf99f94c
Malloc: p1 = 0x9ff4008, 0xbf99f948
strcpy world --->world
Getmem point 0x0, 0xbf99f94c
Getmem point 0x9ff4070, 0xbf99f94c
After p2 = 0x9ff4070, 0xbf99f94c
hello |
|