Trong dự án của tôi, tôi có một phương thức tạo chuỗi từ các số nguyên (sử dụng strcat) và ghi nó vào một tệp. Thật không may nó có một rò rỉ bộ nhớ. Trong khi theo dõi sự rò rỉ đó, tôi đã đơn giản hóa mã của mình như sau. Tôi dường như không thể xác định vị trí hoặc thậm chí sửa chữa nó. Đây là mã:Lỗ hổng bộ nhớ trong mã này ở đâu và cách khắc phục?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char* output = "\0";
int counter = 5;
while(counter > 0)
{
char buffer[20];
sprintf(buffer, "%u", counter);
char* temp;
temp = malloc((strlen(output) + strlen(buffer) + 1));
strcpy(temp, buffer);
strcat(temp, output);
char* oldmemory = output;
output = temp;
free(oldmemory);
counter--;
}
printf("output: %s\n", output);
free(output);
return 0;
}
Valgrind lợi nhuận:
==7125== Memcheck, a memory error detector
==7125== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==7125== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==7125== Command: ./foo
==7125== Parent PID: 4455
==7125==
==7125== Invalid free()/delete/delete[]
==7125== at 0x4024B3A: free (vg_replace_malloc.c:366)
==7125== by 0x8048662: main (foo.c:20)
==7125== Address 0x8048780 is not stack'd, malloc'd or (recently) free'd
==7125==
==7125==
==7125== HEAP SUMMARY:
==7125== in use at exit: 0 bytes in 0 blocks
==7125== total heap usage: 5 allocs, 6 frees, 20 bytes allocated
==7125==
==7125== All heap blocks were freed -- no leaks are possible
==7125==
==7125== For counts of detected and suppressed errors, rerun with: -v
==7125== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 15 from 8)
là rò rỉ bộ nhớ và làm thế nào tôi có thể sửa chữa nó ở đâu?
+1 để được giải thích rõ ràng. – RBerteig