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

问题描述 投票:0回答:1

[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== 
c dynamic-memory-allocation realloc calloc alloc
1个回答
0
投票

答案:

void* calloc( size_t num, size_t size );

Calloc实际上将num和size相乘。

© www.soinside.com 2019 - 2024. All rights reserved.