返回信息流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++.
这是一条镜像帖。来源:北邮人论坛 / cpp / #73927同步于 2013/9/26
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
这样会有内存泄露么?
youziboy
2013/9/26镜像同步16 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
//
#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
: {
: ...................
【 在 tonyjansan 的大作中提到: 】
: [code=c]
: //
: #include <cstdio>
: ...................
free之后要NULL
谢谢你的这个解释。这个其实我也知道, new要相应的delete, malloc要相应的free.
我的疑问是,如果没有new,也没有malloc,而使用delete/free,为啥程序不crash啊。我用的是Devc++
【 在 tonyjansan 的大作中提到: 】
: [code=c]
: //
: #include <cstdio>
: ...................
【 在 youziboy 的大作中提到: 】
: 谢谢你的这个解释。这个其实我也知道, new要相应的delete, malloc要相应的free.
: 我的疑问是,如果没有new,也没有malloc,而使用delete/free,为啥程序不crash啊。我用的是Devc++
just like
公仆们corrupt != 一定进监狱
,
heap corrupt != 一定会crash。