Car*_*rta 1 c memory-leaks realloc calloc
我用calloc函数分配了一个字符串:
//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, sizeof(char));
Run Code Online (Sandbox Code Playgroud)
现在我想用不同的字符串在stringClone上做同样的事情。正在做:
stringClone = calloc(strlen(string2) + 1, sizeof(char));
Run Code Online (Sandbox Code Playgroud)
我会有一些内存泄漏,对吧?在这种情况下我应该如何使用realloc?
您可以使用realloc()通过分配的重新分配内存malloc(),calloc(),realloc(),aligned_alloc()或strdup()。请注意,如果重新分配的块大于由 返回的原始块calloc(),则新分配的部分将不会被初始化为所有位为零。
但是请注意,for 的语法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);
}
Run Code Online (Sandbox Code Playgroud)
由于您似乎并不关心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);
Run Code Online (Sandbox Code Playgroud)
另请注意,在符合 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
...
}
Run Code Online (Sandbox Code Playgroud)
另请注意,强制转换malloc,calloc和的返回值realloc在 C 中是不必要的,并且被认为是不好的风格。
| 归档时间: |
|
| 查看次数: |
293 次 |
| 最近记录: |