如何释放重新分配和分配的内存?

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

如何释放在开始时已经重新分配并随后重新分配和重新分配的内存?此ptr是我的尝试,但是valgrind说有6个分配和6个释放,但是肯定丢失了3个块中的90个字节。

char *textInFile = (char *) calloc(currentLength + 1, sizeof(char) * currentLength);
char *currentLine = (char *) calloc(currentLength + 1, sizeof(char) * currentLineLength);
...
while ((textInFile[index] = getc(f)) != EOF) {
    if (index > currentLength - 3) {
        currentLength += 10;
        ptr = textInFile;
        textInFile = (char *) realloc(textInFile, currentLength);
        textInFile = (char *) calloc(currentLength, sizeof(char) * currentLength);
        free(ptr);
    }
    ...
    if (textInFile[index] == '\n') {
        int k = 0;
        for (int i = previousIndex; i < index; i++) {
            if (k > currentLineLength - 3) {
                currentLineLength += 10;
                ptr = currentLine;  
                currentLine = (char *) realloc(currentLine, currentLineLength);
                currentLine = (char *) calloc(currentLineLength, sizeof(char) * currentLineLength);
                free(ptr);
            }
    ...
    index++;
}

== 4426 ==堆摘要:

== 4426 ==在出口处使用:3个块中90字节

== 4426 ==总堆使用量:9个分配,9个释放,14,668个字节分配]

== 4426 ==

== 4426 ==泄漏摘要:

== 4426 ==绝对丢失:90个字节,分为3个块

== 4426 ==间接丢失:0字节,0块中]

== 4426 ==可能丢失:0字节,位于0块中]

== 4426 ==仍可到达:0字节,位于0块中]

== 4426 ==被抑制:0字节,位于0块中]

c malloc dynamic-memory-allocation realloc calloc
1个回答
0
投票

我认为..您误解了realloc

[realloc不是free

您的代码

        textInFile = (char *) realloc(textInFile, currentLength);
        textInFile = (char *) calloc(currentLength, sizeof(char) * currentLength);
        free(ptr);

textInFile分配了两次。.第一个指针泄漏..

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