我正在进行 CS50 练习:许可证。这段代码是从txt文件中读取车牌并打印出来。 有人可以帮我知道为什么我的代码仍然存在内存泄漏吗? 我仍然收到来自 Valgrind 的这条消息:
==11625== 448 bytes in 8 blocks are definitely lost in loss record 1 of 1
==11625== at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==11625== by 0x109227: main (license.c:29)
==11625==
==11625== LEAK SUMMARY:
==11625== definitely lost: 448 bytes in 8 blocks
==11625== indirectly lost: 0 bytes in 0 blocks
==11625== possibly lost: 0 bytes in 0 blocks
==11625== still reachable: 0 bytes in 0 blocks
==11625== suppressed: 0 bytes in 0 blocks
==11625==
==11625== For lists of detected and suppressed errors, rerun with: -s
==11625== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
我以为我已经用这段代码释放了之前由 malloc 声明的所有内存:
while (idx < 8)
{
free(plates[idx]);
idx ++;
}
这是完整代码
#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];
FILE *infile = fopen(argv[1], "r");
int idx = 0;
while (fread(buffer, 1, 7, infile) == 7)
{
// Replace '\n' with '\0'
buffer[6] = '\0';
plates[idx] = malloc (7 * sizeof(char *));
// Save plate number in array
strcpy(plates[idx], buffer);
idx++;
}
for (int i = 0; i < 8; i++)
{
printf("%s\n", plates[i]);
}
//free memory
fclose(infile);
while (idx < 8)
{
free(plates[idx]);
idx ++;
}
return 0;
}
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.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 of character pointers to store plate numbers
char *plates[8];
// create a file pointer to our external text file
FILE *infile = fopen(argv[1], "r");
int idx = 0;
while (fread(buffer, 1, 7, infile) == 7)
{
// Replace '\n' with '\0' turning it into a string
buffer[6] = '\0';
// allocate memory to store a string of the same length as buffer
plates[idx] = malloc(strlen(buffer) + 1);
// check if memory allocation was successful
if (plates[idx] == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
}
// Copy plate number to allocated memory
strcpy(plates[idx], buffer);
idx++;
}
for (int i = 0; i < idx; i++)
{
printf("%s\n", plates[i]);
// Free the allocated memory for each plate number
free(plates[i]);
}
// Close the file
fclose(infile);
return 0;
}