Free()知道要释放多少字节的内存但可以删除[]做同样的事情?如果我们从堆栈而不是堆分配,它们是否可以使用free()和delete []完美地工作?最后一个问题:我们需要在结尾分配NULL吗?
#include <stdio.h>
#include <stdlib.h>
char * malloc2()
{
char * m = (char *)malloc(100);
//so malloc(10000000) cannot cause stack-overflow?
//cast from void * to char *
return m;
}
char * malloc3()
{
static char m[100];
//can [1000000] cause stack overflow?
return m;
}
char * newX()
{
char * output = new char[100];
return output;
}
int main(){
char * p = malloc2();
//sizeof(p) gives 8 because this is on 64 bit OS/CPU
free(p);
//free() knows the size of p is 100.
//Does it matter if this allocation from stack of malloc2()?
p=NULL;
char * q = malloc3();
//again, sizeof(q) fives 8
//is this allocation from stack of malloc3()?
//I dont need to free because that was from an array declaration ?
q=NULL;
//then who deletes that static array from the stack?
char * r = malloc3();
//now r and q point to same memory area ?
// then if I free q, I dont need to free r.
r=NULL;
char * s = newX();
//allocation from stack again?
//sizeof(s) gives 8, how can delete[] know its size?
delete [] s;
s=NULL;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
Kon*_*lph 16
无论是free也不是delete,也delete []有堆栈分配的内存工作.
该规则实际上非常简单:
malloc必须与一个完全配对,free反之亦然.1new必须与一个完全配对,delete反之亦然.new []必须与一个完全配对,delete []反之亦然.结束.
1好吧,我骗了.malloc/ free是困难的,因为这里还有calloc和realloc.这是修正后的规则:
malloc或calloc必须与一个free或多个电话配对realloc.realloc,做不释放内存必须恰好与一个呼叫中进行配对free或realloc.free必须完全属于一个电话malloc,calloc或者realloc.)换句话说,calloc表现得像malloc(为了内存分配).realloc是一个包容中间连杆malloc→ free链-它可以同时取代malloc和free,并且它可以被放置在这样的调用之间.