C中仍然可以访问的内存

时间:2015-10-16 04:27:54

标签: c memory-leaks

在使用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;
    }

2 个答案:

答案 0 :(得分: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;

}

答案 1 :(得分:0)

free返回malloc时,您的代码设置为NULL指针,但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;
}

另外,在date_create()函数中,当我认为您要使用scanf时,可以使用sscanf

所以这一行

scanf(datestr,"%2d/%2d/%4d",pointer->day,pointer->month,pointer->year);

变为

sscanf(datestr,"%2d/%2d/%4d",pointer->day,pointer->month,pointer->year);