-2

Free() knows how many bytes of memory to free but can delete[] do same thing? What if we allocate from stack instead of heap, do they work flawlessly with free() and delete[] ? Last question: do we need to assign to NULL at the end?

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

Thank you.

4

3 回答 3

16

既不free也不delete使用delete []堆栈分配的内存。

规则实际上非常简单:

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

结束。


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

  • 每个mallocor都calloc必须与一个对freeor的调用配对realloc
  • 每一个realloc不释放内存的东西必须与一个对freeor的调用配对realloc
  • (反之亦然:每个都free必须属于对或malloc的一次调用。)callocrealloc

换句话说,calloc表现得像malloc(为了内存分配)。reallocmallocfree链的包容性中间环节——它可以同时替换mallocfree,并且可以放在这些调用之间。

于 2013-07-12T14:29:47.750 回答
1

回答最后一个问题:仅当您的设计需要时才需要将 NULL 存储在指针变量中;它用于指示指针不指向任何东西。在这里这样做只是浪费时间,因为p在函数结束时消失了:

void f() {
    char *p = new char[10];
    delete [] p;
    p = NULL;
}
于 2013-07-12T14:38:15.187 回答
1

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

于 2013-07-12T14:30:44.120 回答