【问题标题】:How to realloc some memory allocated using calloc?如何重新分配使用 calloc 分配的一些内存?
【发布时间】:2019-11-11 21:01:38
【问题描述】:

我已经用 calloc 函数分配了一个字符串:

//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, sizeof(char));

现在我想用不同的字符串对 stringClone 做同样的事情。正在做:

stringClone = calloc(strlen(string2) + 1, sizeof(char));

我会有一些内存泄漏,对吧?在这种情况下我应该如何使用 realloc

【问题讨论】:

  • 请注意,如果您想要一个字符串的克隆,有一个 POSIX 标准函数 strdup 可以在一次调用中执行此操作。

标签: c memory-leaks realloc calloc


【解决方案1】:

您可以使用realloc() 重新分配由malloc()calloc()realloc()aligned_alloc()strdup() 分配的内存。请注意,如果重新分配的块大于 calloc() 返回的原始块,则新分配的部分将不会初始化为所有位为零。

但请注意,realloc() 的语法不是您所使用的:您必须将指针作为第一个参数传递,并将单个 size_t 传递给新大小。此外,如果无法分配新块,则返回NULL,并且不会释放该块,因此不应将返回值直接存储到stringClone

如果你想使用realloc(),你应该这样做:

//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, 1);
...
char *newp = realloc(stringClone, strlen(string2) + 1);
if (newp == NULL) {
    // deal with out of memory condition
    free(stringClone);
}

由于您似乎并不关心 stringClone 的内容是否保留在重新分配的块中,您可能应该简单地写:

//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, 1);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}
strcpy(stringClone, string1);
...
free(stringClone);
stringClone = calloc(strlen(string2) + 1, 1);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}
strcpy(stringClone, string2);

另请注意,在符合 POSIX 的系统上,有一个内存分配函数对您的用例非常有用:strdup(s) 获取指向 C 字符串的指针,分配 strlen(s) + 1 字节,将字符串复制到分配的块并返回它:

//string1 and string2 previously declared
char *stringClone = strdup(string1);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}
...
free(stringClone);
stringClone = strdup(string2);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}

另请注意,在 C 中强制转换 malloccallocrealloc 的返回值是不必要的,并且被认为是不好的风格。

【讨论】:

    【解决方案2】:

    使用realloc 的原因是它保持原始数据完好无损。但是,如果我正确理解您的用例,您打算删除原始数据。在这种情况下,写起来更简单明了:

    char *stringClone = calloc(strlen(string1) + 1, sizeof(char));
    // check for calloc error
    // use stringClone for string1
    free(stringClone);
    stringClone = calloc(strlen(string2) + 1, sizeof(char));
    // check for calloc error
    // use stringClone for string2
    

    calloc 的错误检查比realloc 更简单,因为不需要临时变量。此外,此模式清楚地表明 string1string2 的数组内容不相关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-21
      • 2015-10-31
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2014-07-03
      • 2017-12-07
      相关资源
      最近更新 更多