malloc() 、realloc 和数组

malloc() ,realloc and arrays

我有一个结构,例如

typedef struct bignum {
    long number_of_digits;
    char *digit;
} bignum;

我想声明一个 bignum 类型的数组,数组大小会动态改变,所以我使用了 malloc()realloc() 我可以使用 realloc() 缩小数组而不会出现内存泄漏吗? 收缩代码示例

if(free_slots == 50)
{
    big_num_Arr =(bignum *) realloc  (big_num_Arr,(capacity-40)*sizeof(bignum));
    free_slots = 10;
    capacity -= 40;
}

假设 digit 指针指向 dynamically-allocated 数组,您需要在 realloc() 释放 big_num_Arr 的那些元素之前释放它们。

if(free_slots == 50)
{
    for (int i = 10; i < free_slots; i++) {
        free(big_num_Arr[i].digit);
    }
    big_num_Arr = realloc(big_num_Arr,(capacity-40)*sizeof(bignum));
    free_slots = 10;
    capacity -= 40;
}

另请参阅 Do I cast the result of malloc?

can i shrink the array using realloc() with out memory leaks (?)

是的,但与 OP 的代码不兼容。任何重新分配,即使是缩减的,都可能 return NULL 并且应该检查。

if (free_slots == 50) {
  size_t new_capacity = capacity-40;
  ...
  if (new_capacity > 0) {
    void *new_ptr =  realloc(big_num_Arr, sizeof *big_num_Arr * new_capacity);
    if (new_ptr) {
      big_num_Arr = new_ptr; 
      capacity = new_capacity;
    } else if (new_capacity <= capacity) {
      // perhaps leave values "as is" 
      // big_num_Arr = big_num_Arr; 
      // capacity = capacity;
    } else {
      // allocation failure
      // perhaps leave values "as is", yet return a error
      // big_num_Arr = big_num_Arr; 
      // capacity = capacity;
      return failure;
    }
  } else {
    free(big_num_Arr);
    big_num_Arr = NULL; 
    capacity = 0;
  }