繁体   English   中英

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

[英]How to realloc some memory allocated using 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()分配的内存。 注意,如果重新分配的块大于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的返回值,并且认为样式不好。

使用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是不相关的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM