Würde jemand in der Lage sein zu beleuchten, warum Valgrind dieses Programm als "definitiv verloren: 2 Bytes in 1 Block" Speicherleck einordnet? Ich verstehe, dass die kommentierte Zeile das Problem löst, aber ich verstehe die Klassifizierung nicht. Laut Valgrind-Dokumenten scheint das Speicherleck als "Indirectally Reachable" (Indirekt erreichbar) zu gelten. Ich bin auch neugierig, warum dies sogar als ein Speicherleck gilt und würde eine Erklärung schätzen. Ist es eine gute Übung, alles manuell freizugeben, obwohl das Programm am Ende der main
-Funktion endet?Definitiv verlorene Speicherleck in C-Programm
#include <stdlib.h>
struct wrapper {
char *data;
};
char *strdup(const char *);
struct wrapper *walloc(struct wrapper *root)
{
if (root == NULL){
root = (struct wrapper *) malloc(sizeof(struct wrapper));
root->data = strdup("H");
}
return root;
}
int main(){
struct wrapper *root;
root = NULL;
root = walloc(root);
//free(root->data);
return 0;
}
ist der Valgrind Ausgang:
$ valgrind --leak-check=full ./leak
==26489== Memcheck, a memory error detector
==26489== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==26489== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==26489== Command: ./leak
==26489==
==26489==
==26489== HEAP SUMMARY:
==26489== in use at exit: 2 bytes in 1 blocks
==26489== total heap usage: 2 allocs, 1 frees, 1,790 bytes allocated
==26489==
==26489== 2 bytes in 1 blocks are definitely lost in loss record 1 of 1
==26489== at 0x4C29F90: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==26489== by 0x4EB79C9: strdup (in /usr/lib/libc-2.20.so)
==26489== by 0x400542: walloc (leak.c:13)
==26489== by 0x400542: main (leak.c:23)
==26489==
==26489== LEAK SUMMARY:
==26489== definitely lost: 2 bytes in 1 blocks
==26489== indirectly lost: 0 bytes in 0 blocks
==26489== possibly lost: 0 bytes in 0 blocks
==26489== still reachable: 0 bytes in 0 blocks
==26489== suppressed: 0 bytes in 0 blocks
==26489==
==26489== For counts of detected and suppressed errors, rerun with: -v
==26489== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
„Ist es gute Praxis manuell frei alles, auch wenn das Programm am Ende der Hauptfunktion beendet?“ Ja, tun Sie das immer, auch wenn das Betriebssystem den Speicher freigibt. 'free()' kann Fehler in Ihrem Programm aufdecken, die sonst nur schwer zu finden sind. Es ist eine gute Angewohnheit, die De-Allocation immer direkt nach dem Zuweisen des Zuordnungscodes zu implementieren. – Lundin
Ich sehe das nicht. Ich sehe 8 Bytes definitiv verloren ('root') und 2 Bytes indirekt verloren (' root-> data'). Kannst du die volle Ausgabe von Valgrind posten? –
Sie sollten '#include' da der Compiler ist dann erlaubt, "magische" Dinge mit 'strdup' (und [GCC] (http://gcc.gnu.org/) tut manchmal) –