BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #73927同步于 2013/9/26
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

这样会有内存泄露么?

youziboy
2013/9/26镜像同步16 回复
typedef struct str_elem { int a; int b; }; /*程序不crash*/ void test1() { struct str_elem* ptrTemp; int *ptrA = new int; *ptrA = 100; int *ptrB = new int; *ptrB = 200; cout<<*ptrA<<" " <<*ptrB<<endl; free(ptrTemp); //delete ptrTemp; //也没有crash } /*程序不crash*/ void test2() { struct str_elem* ptrTemp; delete ptrTemp; } /*程序不crash*/ void test3() { struct str_elem* ptrTemp; free ptrTemp; } 这样直接free,delete 一个非堆里面的内存,为啥程序没有crash啊? 我用的编译器是Devc++.
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
amarantine机器人#1 · 2013/9/26
还没malloc就free?
tonyjansan机器人#2 · 2013/9/26
// #include <cstdio> #include <cstdlib> #include <cstring> struct str_elem { int a; int b; }; void test() { struct str_elem* ptr1 = (struct str_elem*)malloc(sizeof(struct str_elem)); struct str_elem* ptr2 = new struct str_elem; ptr1->a = 100; ptr2->a = 100; ptr1->b = 200; ptr2->b = 200; delete ptr2; // delete if new free(ptr1); // free if malloc } 【 在 youziboy 的大作中提到: 】 : [code=c] : typedef struct str_elem : { : ...................
jason90机器人#3 · 2013/9/26
【 在 tonyjansan 的大作中提到: 】 : [code=c] : // : #include <cstdio> : ................... free之后要NULL
shenlei机器人#4 · 2013/9/26
虽然这是个好习惯,但是这里没有任何必要,不要教条。 【 在 jason90 的大作中提到: 】 : free之后要NULL
zxy机器人#5 · 2013/9/26
= =槽点太多了
ForAlice机器人#6 · 2013/9/26
顶ls
youziboy机器人#7 · 2013/9/27
谢谢你的这个解释。这个其实我也知道, new要相应的delete, malloc要相应的free. 我的疑问是,如果没有new,也没有malloc,而使用delete/free,为啥程序不crash啊。我用的是Devc++ 【 在 tonyjansan 的大作中提到: 】 : [code=c] : // : #include <cstdio> : ...................
youziboy机器人#8 · 2013/9/27
但是程序没有crash哦。 【 在 amarantine 的大作中提到: 】 : 还没malloc就free?
fentoyal机器人#9 · 2013/9/27
【 在 youziboy 的大作中提到: 】 : 谢谢你的这个解释。这个其实我也知道, new要相应的delete, malloc要相应的free. : 我的疑问是,如果没有new,也没有malloc,而使用delete/free,为啥程序不crash啊。我用的是Devc++ just like 公仆们corrupt != 一定进监狱 , heap corrupt != 一定会crash。