我正在try 释放作为链接链一部分的不同 struct 所使用的内存. 函数dumpGroupingOrder()应该释放所使用的内存,但一旦使用,整个程序就会停止运行.如果没有它,即使存在内存泄漏,程序也可以正常运行,请参见下面的valgrind输出:
LEAK SUMMARY:
definitely lost: 48 bytes in 1 blocks
indirectly lost: 328 bytes in 11 blocks
有了它,没有内存泄漏,但我得到了一个double free or corruption (out)错误消息,以及来自valgrind的以下错误消息:
Invalid free() / delete / delete[] / realloc()
at 0x48399AB: free (vg_replace_malloc.c:538)
by 0x10929A: dumpGroupingOrder (code-stack.c:54)
by 0x10952F: main (code-stack.c:88)
Address 0x1fff0000b0 is on thread 1's stack
in frame #2, created by main (code-stack.c:74)
下面是用作MWE的整个代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct groupingOrder {
int *taxa;
size_t groupeSize;
long double distance;
struct groupingOrder* next;
};
void addGroup( struct groupingOrder* HEAD, int * groupe, size_t groupeSize, long double distance ) {
struct groupingOrder* temp = HEAD;
// Moving the last unit structure
while( temp->next != NULL ) {
temp = temp->next;
}
// Allocating space for the unit structure
struct groupingOrder* nouveau = malloc( sizeof( struct groupingOrder ) );
nouveau->distance = distance;
nouveau->groupeSize = groupeSize;
// Allocating variable space for the list of taxa to be stored
nouveau->taxa = malloc( groupeSize * sizeof( int ) );
for( int i = 0; i < groupeSize; i++) {
nouveau->taxa[i] = groupe[i];
}
// Linking the new unit structure to the previous one
temp->next = nouveau;
// Specifying the NULL pointer to label the last unit
nouveau->next = NULL;
}
void dumpGroupingOrder( struct groupingOrder* HEAD ) {
struct groupingOrder* temp = HEAD;
while( temp != NULL ) {
// Copying the address of the current unit
struct groupingOrder* dumpTarget = temp;
// Storing the address of the next unit before dumping the
// current one.
temp = temp->next;
// Dumping the current unit and all its allocated variables
if( dumpTarget->taxa != NULL ) {
free( dumpTarget->taxa );
printf( " #" );
}
free( dumpTarget );
printf( "* " );
}
}
void showGroupingOrder( struct groupingOrder* HEAD ) {
struct groupingOrder* temp = HEAD;
while( temp->next != NULL ) {
temp = temp->next;
for( int i = 0; i < temp->groupeSize; i++) {
printf( " %d", temp->taxa[i] );
}
printf( " %Lf\n", temp->distance );
}
}
int main() {
size_t groupeSize[6] = { 2,2,4,2,5,7 };
int groupes[][7] = { {2,3}, {5,1}, {2,3,5,1}, {7,4}, {2,3,5,1,6}, {2,3,5,1,6,7,4} };
struct groupingOrder HEAD = { .next = NULL };
for( int i = 0; i < 6; i++ ){
addGroup( &HEAD, groupes[i], groupeSize[i], 0.0003 );
}
showGroupingOrder( &HEAD );
printf( "\n\n" );
dumpGroupingOrder( &HEAD );
return 0;
}