我正在为一个真正的应用程序项目做 C++ 程序。
我使用 valgrind 进行内存泄漏检查。
我有 :
10 个块中的 160 个字节肯定丢失在 2 的丢失记录 1 ==14312== 在 0x4A0846F: malloc (vg_replace_malloc.c:236)
但是,我调用了 free() 来释放它。
如何解决?为什么我有内存泄漏?
任何帮助将不胜感激。!
代码如下:
#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;
}