cdynamic-memory-allocationrealloccallocalloc

Too much heap memory usage when reallocing


Valgrind says that 42 718 bytes were allocated, however, when I see how many times the reallocation procces is called, it's 3 or 6 times and variables currentLength and currentLineLength are 10 20 30 or 10 20 30 40 50 60, so the problem isn't in the looping.

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 output:

==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== 

Solution

  • Answer:

    void* calloc( size_t num, size_t size );
    

    Calloc actually multiplies the num and size.