我已经使用 calloc 函数分配了一个字符串:
//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, sizeof(char));
现在,我想在 stringClone 上使用不同的字符串执行相同的操作。正在执行:
stringClone = calloc(strlen(string2) + 1, sizeof(char));
我会发生一些内存泄漏,对吗?在这种情况下应该如何使用 realloc ?
答案 0 :(得分:4)
您可以使用import pandas as pd
from pyproj import Proj, transform
inProj, outProj = Proj(init='epsg:4326'), Proj(init='epsg:27700')
df['newLon'], df['newLat'] = transform(inProj, outProj, df['longitude'].tolist(), df['longitude'].tolist())
重新分配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
还请注意,在符合POSIX的系统上,有一个内存分配函数对于您的用例非常有用://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);
获取一个指向C字符串的指针,分配strdup(s)
字节,复制该字符串到分配的块并返回:
strlen(s) + 1
还请注意,在C语言中,强制转换//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
的返回值是不必要的,并且被认为是不好的样式。
答案 1 :(得分:0)
使用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
的检查简单,因为不需要临时变量。另外,此模式清楚表明string1
和string2
的数组内容不相关。