0

how to free the whole memory chunk for a matrix (which was reserved at once)?

#define ROWS 2
#define COLS 3

   int (*p)[COLS] = malloc (sizeof (*p) * ROWS);

   // not important
   for (size_t i = 0; i < ROWS; i++) {
      for (size_t j = 0; j < COLS; j++) {
         p[i][j] = rand() % 10;
      }
   }

   // not important
   for (size_t i = 0; i < ROWS; i++) {
      for (size_t j = 0; j < COLS; j++) {
         printf ("%d\t", p[i][j]);
      }
      putchar ('\n');
   }

   //is that right ???
   free (p);

I know, I could allocate memory for this matrix in another way, but that's not the question.

The question ist, how to work with this chunk of memory in the right way.

EDIT: I'm asking because of this valgrind summary:

==1684== 
==1684== LEAK SUMMARY:
==1684==    definitely lost: 0 bytes in 0 blocks
==1684==    indirectly lost: 0 bytes in 0 blocks
==1684==      possibly lost: 0 bytes in 0 blocks
==1684==    still reachable: 176 bytes in 1 blocks
==1684==         suppressed: 4,096 bytes in 1 blocks
==1684== 

I thought I have some memory leaks.

  • 1
    `free` frees whatever that `malloc` allocates. You're right. – Shambhav Dec 27 '21 at 13:47
  • 1
    What makes you suspect this *isn't* right? – Scott Hunter Dec 27 '21 at 13:48
  • 1
    Your code is correct. BTW it even works with VLA: `int rows, cols; scanf("%d%d", &rows, &cols); /*assume sane values for rows and cols*/ int (*p)[cols] = malloc(rows * sizeof *p); /* ... */ free(p);` – pmg Dec 27 '21 at 13:51
  • 2
    *["still reachable" means your program is probably ok](https://www.cs.cmu.edu/afs/cs.cmu.edu/project/cmt-40/Nice/RuleRefinement/bin/valgrind-3.2.0/docs/html/faq.html#faq.deflost)* – pmg Dec 27 '21 at 14:19

0 Answers0