[英]Still reachable memory in C
使用valgrind检查内存泄漏后,我得到以下结果。
HEAP SUMMARY:
==10299== in use at exit: 2,286 bytes in 68 blocks
==10299== total heap usage: 139 allocs, 71 frees, 164,646 bytes allocated
==10299==
==10299== LEAK SUMMARY:
==10299== definitely lost: 0 bytes in 0 blocks
==10299== indirectly lost: 0 bytes in 0 blocks
==10299== possibly lost: 0 bytes in 0 blocks
==10299== still reachable: 2,286 bytes in 68 blocks
==10299== suppressed: 0 bytes in 0 blocks
==10299== Reachable blocks (those to which a pointer was found) are not shown.
==10299== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==10299==
==10299== For counts of detected and suppressed errors, rerun with: -v
==10299== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
我的目的是尝试使其不可能发生内存泄漏。 我知道使用malloc函数后必须释放内存。 但是即使如此,它仍然给我相同的结果。 因此,我需要帮助才能看到我的编码有什么问题。
下面是我的代码。
struct date
{ int day;
int month;
int year;
};
Date *date_create(char *datestr)
{
//declare Date to pointer from datestr and check the data size of Date
Date *pointer = (Date *) malloc (sizeof(Date));
if(pointer!=NULL)
{
scanf(datestr,"%2d/%2d/%4d",pointer->day,pointer->month,pointer->year);
}
else
{
printf("Error! ");
date_destroy(pointer);
}
return pointer;
}
void date_destroy(Date *d)
{
free(d);
}
int main(){
return 0;
}
如果从main调用函数,则valgrind将在代码中显示内存泄漏。 您不应该转换malloc。 如果您已经成功分配了内存,则只有您可以释放它。 您需要像这样更改代码
Date *date_create(char *datestr)
{
//declare Date to pointer from datestr and check the data size of Date
Date *pointer = malloc (sizeof (Date));
if(pointer!=NULL)
{
scanf(datestr,"%2d/%2d/%4d",pointer->day,pointer->month,pointer->year);
}
else
{
printf("Error! ");
// date_destroy(pointer); Not required
}
if(pointer) { // Free the allocated memory after use
date_destroy(pointer);
}
return pointer;
}
当malloc
返回NULL
,您的代码被设置为free
指针,但是free(NULL)
不执行任何操作。
使用完指针后,需要调用free()
。
int main(void) {
char datestr[64];
Date* dptr;
fgets(datestr, sizeof(datestr), stdin);
dptr = date_create(datestr);
/* do some stuff with Date ptr */
free(dptr); /* now call free */
return 0;
}
另外,在您认为我想使用sscanf
时,在date_create()
函数中使用scanf
。
所以这条线
scanf(datestr,"%2d/%2d/%4d",pointer->day,pointer->month,pointer->year);
变成
sscanf(datestr,"%2d/%2d/%4d",pointer->day,pointer->month,pointer->year);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.