I am doing C++ program for a real application project.
I use valgrind to do memory leak check.
I got :
160 bytes in 10 blocks are definitely lost in loss record 1 of 2
==14312== at 0x4A0846F: malloc (vg_replace_malloc.c:236)
But, I have called free() to release it.
How to fix it ? Why I have memory leak ?
Any help will be appreciated. !
The code is as follows:
#include <stdio.h>
#include <stdlib.h>
int * GetSomeIDs() ;
/*-------- GetSomeIDs-----*/
typedef struct {
char* alias; /* '\0'-terminated C string */
int specific_id;
} aliasID;
int GetNumberOfAliases(void)
{
return 10;
}
aliasID *GetNextAlias(void)
{
aliasID *p = (aliasID *) malloc(sizeof(aliasID)) ;
p->alias = "test alias";
p->specific_id = rand();
return p;
}
int *GetSomeIDs2(aliasID ***a, int *aIDsize , int *idSize)
{
int *ids = (int *) malloc(sizeof(int) * 8) ;
*idSize = 8 ;
int length = GetNumberOfAliases();
*aIDsize = length ;
int i ;
*a = (aliasID**) malloc(sizeof(aliasID*)*length) ;
for(i = 0 ; i < length ; ++i)
{
(*a)[i] = GetNextAlias();
}
return ids;
}
void callGetSomeIDs()
{
aliasID **aD = NULL;
int mySize = -1;
int myidSize = -1;
int *pt = NULL;
pt = GetSomeIDs2(&aD, &mySize, &myidSize);
if (!pt || !aD || mySize <= 0 || myidSize <= 0)
{
printf("there is a runt time error of GetSomeIDs \n");
if (!pt && aD)
{
printf("there is a runt time error of GetSomeIDs pt is NULL \n");
free(aD);
}
if (!aD && pt)
{
printf("there is a runt time error of GetSomeIDs aD is NULL \n");
free(pt);
}
if (!pt && !aD)
{
printf("there is a runt time error of GetSomeIDs aD and pt all NULL \n");
}
exit(1);
}
// print out 8 int
printf("the followings are integers \n");
int i ;
for(i = 0 ; i < myidSize ; ++i )
{
printf("%d " , pt[i]);
}
printf("\n");
// print out alias and ID
printf("the followings are alias and ID \n");
for (i = 0 ; i < mySize ; ++i )
{
printf( "alias is %s " , (*aD[i]).alias) ;
printf( "specific_id is %d", (*aD[i]).specific_id) ;
printf("\n") ;
}
free(pt);
free(aD);
}
int main()
{
callGetSomeIDs();
return 0;
}
You free the array of
aliasIDstructures, but not the allocated entries in the array.Edit:
You allocate first an array of
aliasIDpointers, then for each entry in the array you allocate the actualaliasID. You need to free thealiasIDpointers in the array first before you free the array: