【问题标题】:Is there any difference between allocating realloc() to a different pointer and allocating realloc() to the same one?将 realloc() 分配给不同的指针和将 realloc() 分配给同一个指针之间有什么区别吗?
【发布时间】:2021-09-02 19:15:35
【问题描述】:

我对在 C 中使用动态内存有点陌生,我想知道使用 realloc() 分配给不同的指针和使用 realloc() 分配相同的指针之间是否有任何区别。 例如:

int *ptr = calloc(10,sizeof(int))
ptr=(int*)realloc(ptr,20);

*ptr3;
int *ptr = calloc(10,sizeof(int))
ptr3=(int*)realloc(ptr,20);

我已经执行了这两个代码,并且我发现两个代码之间没有真正的区别(也没有在 opinters 的值和内存分配之间)。 谢谢。

【问题讨论】:

  • 如果realloc 失败,您将在第一种情况下发生内存泄漏
  • 所以这里应该去掉c++这个标签?在c++ 代码中,我们几乎从不使用 calloc 和 realloc 。

标签: c pointers realloc


【解决方案1】:

realloc失败时,前一种情况会出现差异;在这种情况下,它会返回 NULL,但不会返回 free 原来的 ptr 你通过它。通过直接重新分配ptr,您可以在realloc 失败时保证内存泄漏,因为您不再拥有指向free 的原始指针。

here 看到的规范/正确用法使用两个指针,一个是持久的,一个是临时的。 realloc 的结果总是放在临时的,所以它可以被检查(和持久指针 free 失败)。已知重新分配成功后,临时指针替换持久指针(保证与临时指针相同,或者如果分配无法就地完成,则无效)。

【讨论】:

    【解决方案2】:

    对于第一种情况,如果realloc 失败,它会返回一个null 指针。 然后,您将把 null 指针分配给 ptr,从而使 free 无法使用 ptr 最初指向的内存。

    相反,请执行以下操作:

    int* p = malloc( 10 * sizeof( int ) );
    
    /* Take note of the memory size I'm requesting in the 
       realloc call compared to yours. */
    
    int* tmp = NULL;
    if ( ( tmp = realloc( p, 20 * sizeof( int ) ) ) == NULL ) {
        /* We failed to find available memory, but we're 
           still on the hook for freeing the memory pointed to by p. */
    
        free( p );
        return;
    }
    
    /* We were successful in either extending the memory pointed to by p
       or a new block of memory was allocated for us and the memory pointed to by p
       was copied over for us. In either case, you do not have to free p
       before assigning tmp to p. */
    
    p = tmp;
    

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 2013-12-10
      • 2016-11-07
      • 2011-01-26
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 2011-03-19
      相关资源
      最近更新 更多