由于源代码,这个问题有点长,我试图尽可能地简化它。请耐心等待,感谢您的阅读。
我有一个带有可能运行数百万次的循环的应用程序。我想先做一个,然后再做几千到几百万个调用,而不是在那个循环中进行数千到数百万个malloc
/调用。free
malloc
realloc
但是我遇到了一个问题,当我使用realloc
. 如果我使用malloc
,我的内存使用情况很好。
valgrind
如果我使用's memtest在较小的测试数据集上运行,它会使用malloc
或报告没有内存泄漏realloc
。
我已经验证我将每个malloc
-ed(然后是realloc
-ed)对象与相应的free
.
所以,理论上,我没有泄漏内存,只是使用realloc
似乎消耗了我所有可用的 RAM,我想知道为什么以及我能做些什么来解决这个问题。
我最初拥有的是这样的东西,它malloc
可以正常使用和工作:
Malloc代码
void A () {
do {
B();
} while (someConditionThatIsTrueForMillionInstances);
}
void B () {
char *firstString = NULL;
char *secondString = NULL;
char *someOtherString;
/* populate someOtherString with data from stream, for example */
C((const char *)someOtherString, &firstString, &secondString);
fprintf(stderr, "first: [%s] | second: [%s]\n", firstString, secondString);
if (firstString)
free(firstString);
if (secondString)
free(secondString);
}
void C (const char *someOtherString, char **firstString, char **secondString) {
char firstBuffer[BUFLENGTH];
char secondBuffer[BUFLENGTH];
/* populate buffers with some data from tokenizing someOtherString in a special way */
*firstString = malloc(strlen(firstBuffer)+1);
strncpy(*firstString, firstBuffer, strlen(firstBuffer)+1);
*secondString = malloc(strlen(secondBuffer)+1);
strncpy(*secondString, secondBuffer, strlen(secondBuffer)+1);
}
这工作正常。但我想要更快的东西。
现在我测试一个realloc
安排,malloc
它只 -s 一次:
重新定位代码
void A () {
char *firstString = NULL;
char *secondString = NULL;
do {
B(&firstString, &secondString);
} while (someConditionThatIsTrueForMillionInstances);
if (firstString)
free(firstString);
if (secondString)
free(secondString);
}
void B (char **firstString, char **secondString) {
char *someOtherString;
/* populate someOtherString with data from stream, for example */
C((const char *)someOtherString, &(*firstString), &(*secondString));
fprintf(stderr, "first: [%s] | second: [%s]\n", *firstString, *secondString);
}
void C (const char *someOtherString, char **firstString, char **secondString) {
char firstBuffer[BUFLENGTH];
char secondBuffer[BUFLENGTH];
/* populate buffers with some data from tokenizing someOtherString in a special way */
/* realloc should act as malloc on first pass through */
*firstString = realloc(*firstString, strlen(firstBuffer)+1);
strncpy(*firstString, firstBuffer, strlen(firstBuffer)+1);
*secondString = realloc(*secondString, strlen(secondBuffer)+1);
strncpy(*secondString, secondBuffer, strlen(secondBuffer)+1);
}
如果我在使用导致百万循环条件的大型数据集free -m
运行基于此的测试时在命令行上查看输出realloc
,我的内存从 4 GB 下降到 0 并且应用程序崩溃。
我错过了什么realloc
导致这种情况?对不起,如果这是一个愚蠢的问题,并提前感谢您的建议。