[Valgrind说分配了42 718个字节,但是,当我看到调用重新分配过程的次数为3次或6次时,变量currentLength
和currentLineLength
为10 20 30或10 20 30 40 50 60 ,因此问题不在循环中。
char *textInFile = (char *) calloc(currentLength + 1, sizeof(char) * currentLength);
char *currentLine = (char *) calloc(currentLength + 1, sizeof(char) * currentLineLength);
char *ptr, *ptr2;
...
while ((textInFile[index] = getc(f)) != EOF) {
if (index >= currentLength - 2) {
currentLength += 10;
ptr = (char *) realloc(textInFile, currentLength);
textInFile = (char *) calloc(currentLength, sizeof(char) * currentLength);
free(ptr);
}
if (index > 0) {
if (textInFile[index - 1] == '\n') {
goto End;
}
}
if (textInFile[index] == '\n') {
int k = 0;
for (int i = previousIndex; i < index; i++) {
if (k >= currentLineLength - 2) {
printf("\nCurrent Length: %d\n", currentLineLength);
currentLineLength += 10;
ptr2 = (char *) realloc(currentLine, currentLineLength);
currentLine = (char *) calloc(currentLineLength, sizeof(char) * currentLineLength);
free(ptr2);
}
currentLine[k] = textInFile[i];
k++;
}
previousIndex = index + 1;
...
}
End:
index++;
}
free(textInFile);
free(currentLine);
...
valgrind
输出:
==4756==
==4756== HEAP SUMMARY:
==4756== in use at exit: 0 bytes in 0 blocks
==4756== total heap usage: 27 allocs, 27 frees, 42,718 bytes allocated
==4756==
==4756== All heap blocks were freed -- no leaks are possible
==4756==
答案:
void* calloc( size_t num, size_t size );
Calloc实际上将num和size相乘。