gpt4 book ai didi

c - C 中仍可访问内存

转载 作者:行者123 更新时间:2023-11-30 17:09:44 25 4
gpt4 key购买 nike

我使用 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;

}

关于c - C 中仍可访问内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33162569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com