如果分配是在堆栈或堆上完成的,那么free()和delete[]有关系吗
Does it matter for the free() and delete[] if allocation was done on stack or heap?
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;
}
谢谢。
free
、delete
和delete []
都不能使用堆栈分配的内存。
规则其实简单得可笑:
- 每个
malloc
必须与恰好一个free
配对,反之亦然1 - 每个
new
必须与恰好一个delete
配对,反之亦然 - 每个
new []
必须与恰好一个delete []
配对,反之亦然
结束。
1好吧,我撒谎了。malloc
/free
比较难,因为还有calloc
和realloc
。这是修改后的规则:
- 每个
malloc
或calloc
必须与对free
或realloc
的恰好一个呼叫配对 - 每个不释放内存的
realloc
必须与对free
或realloc
的一个调用配对 - (反之亦然:每个
free
必须恰好属于一个对malloc
、calloc
或realloc
的调用。)
换句话说,calloc
的行为类似于malloc
(为了内存分配)。CCD_ 27是CCD_→free
链-它可以替换malloc
和free
,并且可以放在这类调用之间。
您应该永远不要释放或删除堆栈变量。当它们的堆栈帧返回时,它们将自动被销毁。您可以,只删除用new分配的东西,只删除malloc()家族分配的free()东西。
回答最后一个问题:只有在设计需要的情况下,才需要在指针变量中存储NULL;它用来表示指针没有指向任何东西。在这里做这件事只是浪费时间,因为p
在函数的末尾消失:
void f() {
char *p = new char[10];
delete [] p;
p = NULL;
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 如果我已经有一个头,那么模板(-t)文件属于哪里
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 尝试构建"lock-free"数据结构C++
- C++ 运算符修改/元编程策略,用于不那么冗长的语法
- 调用 free() 有时会导致程序崩溃
- Valgrind 大小为 8 且地址 0x5b7e520 的读取无效,在大小为 16 的块内为 0 字节 free'd
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 而不是那么多的 if 语句,我想要一个逻辑,我可以用一个语句或优化的方式来完成
- 为什么 free() 函数不将内存返回给操作系统?
- 在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?
- 如果偶数浮点数(分数数)的模数为 2,那么它不会给出'0'结果!在C++
- C++我们可以取消引用此指针吗?如果是这样,那么如何,如果不是,那为什么?
- 共享内存中的健壮互斥锁不是那么健壮
- "fast"或"normal"在"free(): invalid next size (fast)"中是什么意思?
- 逻辑'double free or corruption (fasttop)'错误
- 如果由不同的线程写入 8 字节,那么现代英特尔 x86 上的 8 字节读取是否保证理智?
- 如果分配是在堆栈或堆上完成的,那么free()和delete[]有关系吗