关于在C中释放malloc()内存的问题

7cjasjjr  于 2023-02-15  发布在  其他
关注(0)|答案(2)|浏览(206)

我正在学习CS50课程(所以请不要给予我完全正确的答案,但请给我指出正确的方向!)
我让我的程序(如下)工作(虽然我不确定我是否做了“正确的方式”);它打印了plates.txt中的8个车牌。然而,valgrind仍然告诉我丢失了一些字节。我确信这与我在循环中分配内存的“temp”有关。我只是不知道如何修复它。如果有人能给我指出正确的方向,那就太好了!

瓦尔格林:

==18649== HEAP SUMMARY:
==18649== in use at exit: 49 bytes in 7 blocks
==18649== total heap usage: 10 allocs, 3 frees, 4,624 bytes allocated
==18649==
==18649== 49 bytes in 7 blocks are definitely lost in loss record 1 of 1
==18649== at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==18649== by 0x109257: main (license.c:39)
==18649==
==18649== LEAK SUMMARY:
==18649== definitely lost: 49 bytes in 7 blocks
==18649== indirectly lost: 0 bytes in 0 blocks
==18649== possibly lost: 0 bytes in 0 blocks
==18649== still reachable: 0 bytes in 0 blocks
==18649== suppressed: 0 bytes in 0 blocks
==18649==
==18649== For lists of detected and suppressed errors, rerun with: -s
==18649== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

程序代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    // Check for command line args
    if (argc != 2)
    {
        printf("Usage: ./read infile\n");
        return 1;
    }

    // Create buffer to read into
    char buffer[7];

    // Create array to store plate numbers
    char *plates[8];

    // Create a pointer that will later point to a place in memory on the heap for strcpy
    char *temp = NULL;

    FILE *infile = fopen(argv[1], "r");

    if (infile == NULL)
    {
        printf("File not found.\n");
        return 1;
    }

    int idx = 0;

    while (fread(buffer, 1, 7, infile) == 7)
    {
        // Replace '\n' with '\0'
        buffer[6] = '\0';

        // Allocate memory to temporarily store buffer contents
        temp = malloc(sizeof(buffer));

        // Copy buffer contents to temp
        strcpy(temp, buffer);

        // Save plate number in array
        plates[idx] = temp;
        idx++;
    }

    fclose(infile);

    for (int i = 0; i < 8; i++)
    {
        printf("%s\n", plates[i]);
    }

    free(temp);

    return 0;
}

我关闭了文件并释放了我在堆中的“temp”位置。然而,我malloc()temp多次,但我不能释放(temp)多次?

rta7y2nd

rta7y2nd1#

free(temp);是错误的,它只删除最后一个分配的项目。
既然在循环中调用了malloc,那么也必须在循环中调用free,经验法则是每个malloc调用都必须与free调用匹配。
所以你必须做一个for循环,遍历char *plates[8];free,每个plates指针指向的所有东西。

jgovgodb

jgovgodb2#

您需要释放所有分配的指针。

for(i = 0; i < idx; i++) 
   free(plates[i]);

你也可以很容易地超越你的数组界限,因为你不检查索引

while (idx < 8 && fread(buffer, 1, 7, infile) == 7)

打印也是错误的,因为你认为你已经读了所有8块。

for (int i = 0; i < idx; i++)
    {
        printf("%s\n", plates[i]);
    }

相关问题