c - 如何重新分配一些使用 calloc 分配的内存?

标签 c memory-leaks realloc calloc

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

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

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

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

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

最佳答案

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

但是请注意,realloc() 的语法不是您所使用的:您必须将指针作为第一个参数传递,并为新大小传递一个 size_t。此外,如果无法分配新 block ,则返回 NULL 并且不会释放该 block ,因此您不应将返回值直接存储到 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 的内容是否保留在重新分配的 block 中,您应该简单地写:

//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 字节,将字符串复制到分配的 block 并返回:

//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
    ...
}

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

关于c - 如何重新分配一些使用 calloc 分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831704/

相关文章:

c++ - 停止使用 libpcap 捕获数据并将其保存在文件中

python - 使用 tensorflow 进行批量矩阵分解中的内存泄漏

通知服务中的android内存泄漏

java - Com4j 因 DirectByteBuffer、Cleaner、Finalizer、Variant 实例而泄漏

c - 重新分配内存并在 C 中重新分配的内存空间添加一个字符串

c++ - 存储 wchar_t 并在显示时有时会更改一些字符

在函数中使用 const 参数的 C 编程

c - 从标准输入读取整数并存储在二维数组中 (C)

windows - Realloc() 在 Windows 中没有正确释放内存

c - 当 realloc 缩小分配的 block 时,释放的内存在哪里?