首页 文章

我们可以使用realloc释放动态分配内存吗?

提问于
浏览
0

我的朋友和我讨论过释放动态分配的内存 . 他告诉我可以使用realloc()释放内存,我否认了这一点 . 我们来考虑以下代码:

int main()
{
    int *p = (int *)malloc(sizeof(int) * 10);
    int *q = (int *)malloc(sizeof(int) * 10);

    free(p);
    p = NULL;

    realloc(q, sizeof(int) * 0);
    q = NULL;

    _getch();
    return 0;
}

我们假设 pq 分别指向地址 0x10000x2000 . 在上面的代码中, pqint 指针,指向RAM中动态分配的40个字节的内存块 . 执行 free(p) 时,释放内存地址( 0x1000 ) . 释放的内存地址( 0x1000 )可以再次由OS使用 . 然后, NULL 被分配给指针变量 p ,以防止 p 成为悬空指针 .

realloc(q, sizeof(int) * 0);

realloc() 只是将 q 指向的内存块缩小为零 . 但 q 仍指向同一地址( 0x2000 ),并且该地址未被释放 . 在为指针 q 分配NULL值时, q 现在指向NULL并且 q 指向的地址( 0x2000 )未被释放,并且到该地址的链接( 0x2000 )将丢失 . 操作系统将来不能使用该地址( 0x2000 ),直到程序结束 .

我的理解是否正确?

2 回答

  • 4

    realloc(, 0)implementation dependent and not equivalentfree() .

    那就是说,你可能很幸运:

    #include <stdio.h>
    #include <malloc.h>
    
    int main() {
            char *a;
            a = malloc(1024);
            printf("a = %08lx\n", a);
            free(a);
            a = malloc(1024);
            printf("a = %08lx\n", a);
            realloc(a, 0);
            a = malloc(1024);
            printf("a = %08lx\n", a);
    }
    
    gcc version 6.1.1 20160815 [gcc-6-branch revision 239479] (SUSE Linux)
    ldd --version
    
    ldd (GNU libc) 2.23
    
    a = 01dad010
    a = 01dad010
    a = 01dad010
    

    所以第二个malloc,在realloc(,0)之后,"sees"之前是一个空闲块 . 我认为这意味着 in this instancerealloc 重复了 free 的行为 . DO NOT RELY ON THIS .

  • 4
    realloc(q, sizeof(int) * 0);
    

    和...一样

    realloc(q, 0);
    

    7.22.3.5中的C标准 - > 2 realloc函数说:

    ..并返回指向具有size指定大小的新对象的指针 . 新对象的内容应与解除分配之前的旧对象的内容相同,直到新旧大小中的较小者为止 .

    但它没有明确说明如果新大小为零会发生什么 . 但是你仍然有一个 artist 指针可以传递给 free .

    考虑

    char *a;
    a=malloc(2*sizeof *a);
    a=realloc(a,0);
    // Note I'm purposely NOT using a temporary variable to store 'realloc' results
    // Moreover, above is BAD practice.
    free(a); // Is this permitted? YES !! Did we technically free memory above? NO !!
    //Compiler will not yell at you for the above, in fact it is legal as per the standard
    return 0; // No output for this one
    

    VS

    char *a;
    a=malloc(2*sizeof *a);
    free(a);
    //You're not suppose to free(a) again.
    free(a); 
    //Compiler will yell at you for the above.
    return 0;
    

    output

    double free or corruption (fasttop): 0x0000000000915010
    

    Conclusions

    • deallocationfreeing 并不完全相同 .

    • reallocfree 都可以解除分配内存,但只有 free 可以释放内存 .


    那就是说

    free(p);
    p = NULL;
    

    是释放内存的推荐方法 . 请检查[ this ]回答 .

相关问题