C: Correctly freeing memory of a multi-dimensional array

后端 未结 5 812
清酒与你
清酒与你 2020-11-28 04:00

Say you have the following ANSI C code that initializes a multi-dimensional array :

int main()
{
      int i, m = 5, n = 20;
      int **a = malloc(m * sizeo         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 04:49

    Undo exactly what you allocated:

      for (i = 0; i < m; i++) { 
          free(a[i]);
      }
      free(a);
    

    Note that you must do this in the reverse order from which you originally allocated the memory. If you did free(a) first, then a[i] would be accessing memory after it had been freed, which is undefined behaviour.

提交回复
热议问题