Using free() on pointers of two dimensional array with multiple malloc()?










2















I have a function that allocates a two dimensional array within a function returning a pointer to the array. Creating the array requires an array of pointers each of which contains the address of a row of the two dimensional array.



How do I correctly free these two malloc() calls outside of this function once I am done with this array?



int** allocateMatrix(int rows, int cols)

int* arr = malloc(rows*cols*sizeof(int));
int** matrix = malloc(rows*sizeof(int*));
int i;
for(i=0; i<rows; i++)

matrix[i] = &(arr[i*cols]);

return matrix;



The function is used like this:



int** 2d_arr = allocateMatrix(row,cols);


Thanks!










share|improve this question




























    2















    I have a function that allocates a two dimensional array within a function returning a pointer to the array. Creating the array requires an array of pointers each of which contains the address of a row of the two dimensional array.



    How do I correctly free these two malloc() calls outside of this function once I am done with this array?



    int** allocateMatrix(int rows, int cols)

    int* arr = malloc(rows*cols*sizeof(int));
    int** matrix = malloc(rows*sizeof(int*));
    int i;
    for(i=0; i<rows; i++)

    matrix[i] = &(arr[i*cols]);

    return matrix;



    The function is used like this:



    int** 2d_arr = allocateMatrix(row,cols);


    Thanks!










    share|improve this question


























      2












      2








      2








      I have a function that allocates a two dimensional array within a function returning a pointer to the array. Creating the array requires an array of pointers each of which contains the address of a row of the two dimensional array.



      How do I correctly free these two malloc() calls outside of this function once I am done with this array?



      int** allocateMatrix(int rows, int cols)

      int* arr = malloc(rows*cols*sizeof(int));
      int** matrix = malloc(rows*sizeof(int*));
      int i;
      for(i=0; i<rows; i++)

      matrix[i] = &(arr[i*cols]);

      return matrix;



      The function is used like this:



      int** 2d_arr = allocateMatrix(row,cols);


      Thanks!










      share|improve this question
















      I have a function that allocates a two dimensional array within a function returning a pointer to the array. Creating the array requires an array of pointers each of which contains the address of a row of the two dimensional array.



      How do I correctly free these two malloc() calls outside of this function once I am done with this array?



      int** allocateMatrix(int rows, int cols)

      int* arr = malloc(rows*cols*sizeof(int));
      int** matrix = malloc(rows*sizeof(int*));
      int i;
      for(i=0; i<rows; i++)

      matrix[i] = &(arr[i*cols]);

      return matrix;



      The function is used like this:



      int** 2d_arr = allocateMatrix(row,cols);


      Thanks!







      c function pointers multidimensional-array free






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 4:36









      Richard Chambers

      10.1k24268




      10.1k24268










      asked Nov 15 '18 at 18:50









      Tim WeissenfelsTim Weissenfels

      149




      149






















          3 Answers
          3






          active

          oldest

          votes


















          4














          You can only pass to free what was received from malloc. So the number of calls to free must be the same as the number of calls to malloc.



          The first row of 2d_arr, i.e. 2d_arr[0], contains &arr[0*cols] == &arr[0] == arr. So you want to free that and matrix itself:



          free(2d_arr[0]);
          free(2d_arr);





          share|improve this answer

























          • Is it ok when i do: free(2d_arr[0]); outside the func

            – Tim Weissenfels
            Nov 15 '18 at 19:09











          • @TimWeissenfels Yes, since 2d_arr contains the same value as matrix, the effect is the same.

            – dbush
            Nov 15 '18 at 19:10











          • Thank you for your quick response! but what I do not understand is why I only have to free() the first index from matrix :)

            – Tim Weissenfels
            Nov 15 '18 at 19:16











          • @TimWeissenfels You can only pass to free what was passed to malloc. So two of each.

            – dbush
            Nov 15 '18 at 19:20











          • Ok! Thank you btw cool implementation of merge sort :)

            – Tim Weissenfels
            Nov 15 '18 at 19:22


















          0














          This will work:



          void freeMatrix( int **matrix )

          free( matrix[ 0 ] );
          free( matrix );



          Because, for i == 0, this code



          matrix[i] = &(arr[i*cols]);


          sets matrix[ 0 ] to the address of arr[0], which is the same value returned from the first malloc call:



          int* arr = malloc(rows*cols*sizeof(int));


          It's clearer if you write matrix allocation like



          int** allocateMatrix(int rows, int cols)

          int** matrix = malloc(rows*sizeof(int*));
          matrix[ 0 ] = malloc(rows*cols*sizeof(int));

          int i;
          for(i=1; i<rows; i++)

          matrix[i] = &(arr[i*cols]);

          return matrix;



          Note the change in malloc() order, the direct assignment to matrix[ 0 ], and the change in loop index to start at 1.






          share|improve this answer






























            0














            I suggest that you use a single malloc() to allocate the entire memory area so as to make it easier to manage as a single pointer.



            I believe the following modified version of your function should work.



            int** allocateMatrix(int rows, int cols)

            size_t sMemSize = rows*sizeof(int*) + rows*cols*sizeof(int);
            int** matrix = malloc(sMemSize);
            int* arr = (int *) (matrix + rows);
            int i;
            for(i=0; i<rows; i++)

            matrix[i] = &(arr[i*cols]);

            return matrix;



            Then you can just do free(2d_arr); where int** 2d_arr = allocateMatrix (nRows, nCols);.






            share|improve this answer






















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53326113%2fusing-free-on-pointers-of-two-dimensional-array-with-multiple-malloc%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              4














              You can only pass to free what was received from malloc. So the number of calls to free must be the same as the number of calls to malloc.



              The first row of 2d_arr, i.e. 2d_arr[0], contains &arr[0*cols] == &arr[0] == arr. So you want to free that and matrix itself:



              free(2d_arr[0]);
              free(2d_arr);





              share|improve this answer

























              • Is it ok when i do: free(2d_arr[0]); outside the func

                – Tim Weissenfels
                Nov 15 '18 at 19:09











              • @TimWeissenfels Yes, since 2d_arr contains the same value as matrix, the effect is the same.

                – dbush
                Nov 15 '18 at 19:10











              • Thank you for your quick response! but what I do not understand is why I only have to free() the first index from matrix :)

                – Tim Weissenfels
                Nov 15 '18 at 19:16











              • @TimWeissenfels You can only pass to free what was passed to malloc. So two of each.

                – dbush
                Nov 15 '18 at 19:20











              • Ok! Thank you btw cool implementation of merge sort :)

                – Tim Weissenfels
                Nov 15 '18 at 19:22















              4














              You can only pass to free what was received from malloc. So the number of calls to free must be the same as the number of calls to malloc.



              The first row of 2d_arr, i.e. 2d_arr[0], contains &arr[0*cols] == &arr[0] == arr. So you want to free that and matrix itself:



              free(2d_arr[0]);
              free(2d_arr);





              share|improve this answer

























              • Is it ok when i do: free(2d_arr[0]); outside the func

                – Tim Weissenfels
                Nov 15 '18 at 19:09











              • @TimWeissenfels Yes, since 2d_arr contains the same value as matrix, the effect is the same.

                – dbush
                Nov 15 '18 at 19:10











              • Thank you for your quick response! but what I do not understand is why I only have to free() the first index from matrix :)

                – Tim Weissenfels
                Nov 15 '18 at 19:16











              • @TimWeissenfels You can only pass to free what was passed to malloc. So two of each.

                – dbush
                Nov 15 '18 at 19:20











              • Ok! Thank you btw cool implementation of merge sort :)

                – Tim Weissenfels
                Nov 15 '18 at 19:22













              4












              4








              4







              You can only pass to free what was received from malloc. So the number of calls to free must be the same as the number of calls to malloc.



              The first row of 2d_arr, i.e. 2d_arr[0], contains &arr[0*cols] == &arr[0] == arr. So you want to free that and matrix itself:



              free(2d_arr[0]);
              free(2d_arr);





              share|improve this answer















              You can only pass to free what was received from malloc. So the number of calls to free must be the same as the number of calls to malloc.



              The first row of 2d_arr, i.e. 2d_arr[0], contains &arr[0*cols] == &arr[0] == arr. So you want to free that and matrix itself:



              free(2d_arr[0]);
              free(2d_arr);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 15 '18 at 19:20

























              answered Nov 15 '18 at 18:52









              dbushdbush

              103k13108145




              103k13108145












              • Is it ok when i do: free(2d_arr[0]); outside the func

                – Tim Weissenfels
                Nov 15 '18 at 19:09











              • @TimWeissenfels Yes, since 2d_arr contains the same value as matrix, the effect is the same.

                – dbush
                Nov 15 '18 at 19:10











              • Thank you for your quick response! but what I do not understand is why I only have to free() the first index from matrix :)

                – Tim Weissenfels
                Nov 15 '18 at 19:16











              • @TimWeissenfels You can only pass to free what was passed to malloc. So two of each.

                – dbush
                Nov 15 '18 at 19:20











              • Ok! Thank you btw cool implementation of merge sort :)

                – Tim Weissenfels
                Nov 15 '18 at 19:22

















              • Is it ok when i do: free(2d_arr[0]); outside the func

                – Tim Weissenfels
                Nov 15 '18 at 19:09











              • @TimWeissenfels Yes, since 2d_arr contains the same value as matrix, the effect is the same.

                – dbush
                Nov 15 '18 at 19:10











              • Thank you for your quick response! but what I do not understand is why I only have to free() the first index from matrix :)

                – Tim Weissenfels
                Nov 15 '18 at 19:16











              • @TimWeissenfels You can only pass to free what was passed to malloc. So two of each.

                – dbush
                Nov 15 '18 at 19:20











              • Ok! Thank you btw cool implementation of merge sort :)

                – Tim Weissenfels
                Nov 15 '18 at 19:22
















              Is it ok when i do: free(2d_arr[0]); outside the func

              – Tim Weissenfels
              Nov 15 '18 at 19:09





              Is it ok when i do: free(2d_arr[0]); outside the func

              – Tim Weissenfels
              Nov 15 '18 at 19:09













              @TimWeissenfels Yes, since 2d_arr contains the same value as matrix, the effect is the same.

              – dbush
              Nov 15 '18 at 19:10





              @TimWeissenfels Yes, since 2d_arr contains the same value as matrix, the effect is the same.

              – dbush
              Nov 15 '18 at 19:10













              Thank you for your quick response! but what I do not understand is why I only have to free() the first index from matrix :)

              – Tim Weissenfels
              Nov 15 '18 at 19:16





              Thank you for your quick response! but what I do not understand is why I only have to free() the first index from matrix :)

              – Tim Weissenfels
              Nov 15 '18 at 19:16













              @TimWeissenfels You can only pass to free what was passed to malloc. So two of each.

              – dbush
              Nov 15 '18 at 19:20





              @TimWeissenfels You can only pass to free what was passed to malloc. So two of each.

              – dbush
              Nov 15 '18 at 19:20













              Ok! Thank you btw cool implementation of merge sort :)

              – Tim Weissenfels
              Nov 15 '18 at 19:22





              Ok! Thank you btw cool implementation of merge sort :)

              – Tim Weissenfels
              Nov 15 '18 at 19:22













              0














              This will work:



              void freeMatrix( int **matrix )

              free( matrix[ 0 ] );
              free( matrix );



              Because, for i == 0, this code



              matrix[i] = &(arr[i*cols]);


              sets matrix[ 0 ] to the address of arr[0], which is the same value returned from the first malloc call:



              int* arr = malloc(rows*cols*sizeof(int));


              It's clearer if you write matrix allocation like



              int** allocateMatrix(int rows, int cols)

              int** matrix = malloc(rows*sizeof(int*));
              matrix[ 0 ] = malloc(rows*cols*sizeof(int));

              int i;
              for(i=1; i<rows; i++)

              matrix[i] = &(arr[i*cols]);

              return matrix;



              Note the change in malloc() order, the direct assignment to matrix[ 0 ], and the change in loop index to start at 1.






              share|improve this answer



























                0














                This will work:



                void freeMatrix( int **matrix )

                free( matrix[ 0 ] );
                free( matrix );



                Because, for i == 0, this code



                matrix[i] = &(arr[i*cols]);


                sets matrix[ 0 ] to the address of arr[0], which is the same value returned from the first malloc call:



                int* arr = malloc(rows*cols*sizeof(int));


                It's clearer if you write matrix allocation like



                int** allocateMatrix(int rows, int cols)

                int** matrix = malloc(rows*sizeof(int*));
                matrix[ 0 ] = malloc(rows*cols*sizeof(int));

                int i;
                for(i=1; i<rows; i++)

                matrix[i] = &(arr[i*cols]);

                return matrix;



                Note the change in malloc() order, the direct assignment to matrix[ 0 ], and the change in loop index to start at 1.






                share|improve this answer

























                  0












                  0








                  0







                  This will work:



                  void freeMatrix( int **matrix )

                  free( matrix[ 0 ] );
                  free( matrix );



                  Because, for i == 0, this code



                  matrix[i] = &(arr[i*cols]);


                  sets matrix[ 0 ] to the address of arr[0], which is the same value returned from the first malloc call:



                  int* arr = malloc(rows*cols*sizeof(int));


                  It's clearer if you write matrix allocation like



                  int** allocateMatrix(int rows, int cols)

                  int** matrix = malloc(rows*sizeof(int*));
                  matrix[ 0 ] = malloc(rows*cols*sizeof(int));

                  int i;
                  for(i=1; i<rows; i++)

                  matrix[i] = &(arr[i*cols]);

                  return matrix;



                  Note the change in malloc() order, the direct assignment to matrix[ 0 ], and the change in loop index to start at 1.






                  share|improve this answer













                  This will work:



                  void freeMatrix( int **matrix )

                  free( matrix[ 0 ] );
                  free( matrix );



                  Because, for i == 0, this code



                  matrix[i] = &(arr[i*cols]);


                  sets matrix[ 0 ] to the address of arr[0], which is the same value returned from the first malloc call:



                  int* arr = malloc(rows*cols*sizeof(int));


                  It's clearer if you write matrix allocation like



                  int** allocateMatrix(int rows, int cols)

                  int** matrix = malloc(rows*sizeof(int*));
                  matrix[ 0 ] = malloc(rows*cols*sizeof(int));

                  int i;
                  for(i=1; i<rows; i++)

                  matrix[i] = &(arr[i*cols]);

                  return matrix;



                  Note the change in malloc() order, the direct assignment to matrix[ 0 ], and the change in loop index to start at 1.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 18:54









                  Andrew HenleAndrew Henle

                  20.5k31435




                  20.5k31435





















                      0














                      I suggest that you use a single malloc() to allocate the entire memory area so as to make it easier to manage as a single pointer.



                      I believe the following modified version of your function should work.



                      int** allocateMatrix(int rows, int cols)

                      size_t sMemSize = rows*sizeof(int*) + rows*cols*sizeof(int);
                      int** matrix = malloc(sMemSize);
                      int* arr = (int *) (matrix + rows);
                      int i;
                      for(i=0; i<rows; i++)

                      matrix[i] = &(arr[i*cols]);

                      return matrix;



                      Then you can just do free(2d_arr); where int** 2d_arr = allocateMatrix (nRows, nCols);.






                      share|improve this answer



























                        0














                        I suggest that you use a single malloc() to allocate the entire memory area so as to make it easier to manage as a single pointer.



                        I believe the following modified version of your function should work.



                        int** allocateMatrix(int rows, int cols)

                        size_t sMemSize = rows*sizeof(int*) + rows*cols*sizeof(int);
                        int** matrix = malloc(sMemSize);
                        int* arr = (int *) (matrix + rows);
                        int i;
                        for(i=0; i<rows; i++)

                        matrix[i] = &(arr[i*cols]);

                        return matrix;



                        Then you can just do free(2d_arr); where int** 2d_arr = allocateMatrix (nRows, nCols);.






                        share|improve this answer

























                          0












                          0








                          0







                          I suggest that you use a single malloc() to allocate the entire memory area so as to make it easier to manage as a single pointer.



                          I believe the following modified version of your function should work.



                          int** allocateMatrix(int rows, int cols)

                          size_t sMemSize = rows*sizeof(int*) + rows*cols*sizeof(int);
                          int** matrix = malloc(sMemSize);
                          int* arr = (int *) (matrix + rows);
                          int i;
                          for(i=0; i<rows; i++)

                          matrix[i] = &(arr[i*cols]);

                          return matrix;



                          Then you can just do free(2d_arr); where int** 2d_arr = allocateMatrix (nRows, nCols);.






                          share|improve this answer













                          I suggest that you use a single malloc() to allocate the entire memory area so as to make it easier to manage as a single pointer.



                          I believe the following modified version of your function should work.



                          int** allocateMatrix(int rows, int cols)

                          size_t sMemSize = rows*sizeof(int*) + rows*cols*sizeof(int);
                          int** matrix = malloc(sMemSize);
                          int* arr = (int *) (matrix + rows);
                          int i;
                          for(i=0; i<rows; i++)

                          matrix[i] = &(arr[i*cols]);

                          return matrix;



                          Then you can just do free(2d_arr); where int** 2d_arr = allocateMatrix (nRows, nCols);.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 15 '18 at 19:41









                          Richard ChambersRichard Chambers

                          10.1k24268




                          10.1k24268



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53326113%2fusing-free-on-pointers-of-two-dimensional-array-with-multiple-malloc%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Top Tejano songwriter Luis Silva dead of heart attack at 64

                              政党

                              天津地下鉄3号線