检查C中的内存释放是否正确
大家好 我正在尝试用C语言制作一个ascii俄罗斯方块 然而,我对指针还不是很有经验,所以我想问一下,我所做的这些函数,分配和释放内存是否正确(这意味着它们不会留下内存泄漏) 这是我用来创建俄罗斯方块的函数:检查C中的内存释放是否正确,c,function,memory,malloc,free,C,Function,Memory,Malloc,Free,大家好 我正在尝试用C语言制作一个ascii俄罗斯方块 然而,我对指针还不是很有经验,所以我想问一下,我所做的这些函数,分配和释放内存是否正确(这意味着它们不会留下内存泄漏) 这是我用来创建俄罗斯方块的函数: char** InitTetris( int size_x , int size_y ) { /* InitTetris allocates memory for the tetris array. This function should be calle
char** InitTetris( int size_x , int size_y )
{
/*
InitTetris allocates memory for the tetris array.
This function should be called only once at the beginning of the game.
*/
//Variables
int i;
char** tetris = NULL;
//Allocate memory
tetris = ( char** ) malloc ( size_x * sizeof ( char* ) );
for ( i = 0 ; i < size_x ; i++ )
{
tetris[i] = ( char* ) malloc ( size_y * sizeof ( char ) );
}
return tetris;
}//End of InitTetris
程序一切正常,我只是想确保我不会乱扔垃圾。。。你能检查一下我的方法吗?看起来还可以。在创建内存时,最好检查malloc是否不返回
NULL
。内存泄漏的最佳朋友是C编程的好指南。这里有很多。
之后考虑ValGRIND或EFINCE(Linux)等工具,
efence附带了一些linux发行版
Windows也有堆分析工具,例如在XP上:
我想你没事。正如@Hassan Matar所说,这是值得做的。 不过,还有一件事。我在这里学到,在stackoverflow中,不铸造Malloc是铸造Malloc的更好选择 如果你告诉你的编译器你(可能)知道你正在使用的数据类型,那么你可能会得到的错误数量是不值得冒险的
检查此项以了解更多详细信息。检查是否有任何内存无法分配,因为如果从未分配过内存,释放可能会导致崩溃:
//In InitTetris:
tetris = ( char** ) malloc ( size_x * sizeof ( char* ) );
//if tetris == NULL, then exit from the function with a failure code
//and don't continue the rest of the program.
//
有关malloc失败可能性的更多信息,请参阅以下URL:
堆栈溢出不是代码评估站点。视情况与同事或同学核实。也许他们会有输入。你用的是什么操作系统?如果您使用的是Windows,我建议您购买windbg的副本并学习如何使用它。它可以帮助您追踪代码中的内存泄漏。一些教程可以在Unix系统中找到,如果在UNIX系统中考虑的话,我在高中…没有人会@谢谢你的链接@E.Z.Hart。。。我很乐意帮忙。祝你好运
void NewGame()
{
//Variables
char** tetris; /* Array that contains the game board */
int size_x , size_y; /* Size of tetris array */
//Initialize tetris array
tetris = InitTetris( size_x , size_y );
//Do stuff.....
//Free tetris array
ExitTetris( tetris , size_y );
}//End of NewGame
//In InitTetris:
tetris = ( char** ) malloc ( size_x * sizeof ( char* ) );
//if tetris == NULL, then exit from the function with a failure code
//and don't continue the rest of the program.
//