我用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
...
}
另请注意,强制转换 malloc
、calloc
和 realloc
的返回值在 C 中是不必要的,并且被认为是糟糕的风格。
关于c - 如何重新分配一些使用 calloc 分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831704/