如果分配是在堆栈或堆上完成的,那么free()和delete[]有关系吗

Does it matter for the free() and delete[] if allocation was done on stack or heap?

本文关键字:free 那么 delete 有关系 堆栈 分配 如果      更新时间:2023-10-16

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;
}

谢谢。

freedeletedelete []都不能使用堆栈分配的内存。

规则其实简单得可笑:

  • 每个malloc必须与恰好一个free配对,反之亦然1
  • 每个new必须与恰好一个delete配对,反之亦然
  • 每个new []必须与恰好一个delete []配对,反之亦然

结束。


1好吧,我撒谎了。malloc/free比较难,因为还有callocrealloc。这是修改后的规则:

  • 每个malloccalloc必须与对freerealloc的恰好一个呼叫配对
  • 每个释放内存的realloc必须与对freerealloc的一个调用配对
  • (反之亦然:每个free必须恰好属于一个对malloccallocrealloc的调用。)

换句话说,calloc的行为类似于malloc(为了内存分配)。CCD_ 27是CCD_→free链-它可以替换mallocfree,并且可以放在这类调用之间。

您应该永远不要释放或删除堆栈变量。当它们的堆栈帧返回时,它们将自动被销毁。您可以,只删除用new分配的东西,只删除malloc()家族分配的free()东西。

回答最后一个问题:只有在设计需要的情况下,才需要在指针变量中存储NULL;它用来表示指针没有指向任何东西。在这里做这件事只是浪费时间,因为p在函数的末尾消失:

void f() {
    char *p = new char[10];
    delete [] p;
    p = NULL;
}
相关文章: