重新分配时堆内存使用过多

Too much heap memory usage when reallocing

Valgrind 说分配了 42 718 字节,但是,当我看到重新分配过程被调用了多少次时,它是 3 或 6 次,变量 currentLengthcurrentLineLength 是 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 相乘。