0

大家好!

我正在尝试用 C 制作一个 ascii 俄罗斯方块。

但是我对指针的经验还不是很丰富,所以我想问一下我是否正确创建了这些函数,分配和释放内存(这意味着它们不会留下内存泄漏)。

这是我用来创建俄罗斯方块板的函数:

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

这是释放内存的功能:

void ExitTetris ( char** tetris , int size_y )
{
   /*
      This function is called once at the end of the game to
      free the memory allocated for the tetris array.
   */

   //Variables
   int i;

   //Free memory
   for ( i = 0 ; i < size_y ; i++ )
   {
      free( tetris[i] );
   }

   free( tetris );

 }//End of ExitTetris    

从另一个函数处理的所有内容

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

程序上一切正常,我只是想确保我不会乱扔人们的内存……你能检查我的方法吗?

4

4 回答 4

2

您最好的内存泄漏朋友是 C 编程的好指南。有很多可用的。之后考虑一些工具,如 valgrind 或 efence (linux),

http://valgrind.org/

efence 带有一些 linux 发行版。

Windows 也有堆分析工具,例如在 XP 上:

http://support.microsoft.com/kb/268343

于 2013-01-08T23:50:28.260 回答
0

好像没问题。NULL最好在创建内存时检查 malloc 是否没有返回。

于 2013-01-08T23:44:33.080 回答
0

我觉得你没事。正如@Hassan Matar 所说,这是值得的。不过,还有一件事。我在这里了解到,在 stackoverflow 中,不投射 malloc 是投射它们的更好选择。

告诉编译器您(可能)知道您正在使用的数据类型可能会出现的错误数量不值得冒险。

检查此问题以获取更多详细信息。

于 2013-01-08T23:59:33.030 回答
0

检查是否有任何内存无法分配,因为如果从未分配内存,释放可能会导致崩溃:

//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:

如何检测malloc失败?

于 2013-01-09T00:04:49.160 回答