您可以使用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 中强制转换 malloc、calloc 和 realloc 的返回值是不必要的,并且被认为是不好的风格。