0

So I have a matrix which was created this way :

 int **mat(int nl, int nc) {
  int i;
  int **v = malloc(nl * sizeof(int *));

  for (i = 0; i < nl; i++) {
    v[i] = calloc(nc, sizeof(int));
  }
  return v;
}

Let's say after the input , it is :

0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7

I would want to keep only the first 2 rows and first 3 columns , and free the memory of the other rows and columns , so it would look like :

0 1 2
1 2 3

How do I do that ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Andrei
  • 31
  • 1
  • 8
  • 2
    There is no matrix (aka 2D array) in you code. `int **` is not a 2D array, cannot point to one or represent one. Why do you want to free the memory? Just don't use all space. There hardly is anything gained with partial freeing, you just frament memory space. – too honest for this site Dec 01 '16 at 18:29
  • I see your point. But if you have big rows like 10000 elements and resize to, say 4000 elements, it could be interesting because you would have room for another "matrix" like this, and there would not be any memory copy in the `realloc` process. Memory is fragmented, but so are the matrixes. It depends on the difference of row sizes before/after resize. – Jean-François Fabre Dec 01 '16 at 18:45

1 Answers1

2

you would have to:

  • free the full rows after the 2 first ones (and set nl to 2):

like this:

for (i = 2; i < nl; i++) {
    free(v[i]);
  }
nl = 2;
  • perform a realloc of the remaining rows (set nc to 3 as well)
  • check realloc return code. In the unlikely case it would return NULL, fallback to keeping your old array (reference)

like this:

  nc = 3;
  for (i = 0; i < nl; i++) {
    int *new_v = realloc(v[i], nc*sizeof(int));
    if (new_v!=NULL)
    {
       v[i] = new_v;
    }
  }

Edit: if you didn't change nc and print the "old" values, it would appear to have done nothing because the old values could be still there (freeing does not mean resetting the memory), but you may access unallocated data now: performing another allocation can reuse the freed data and overwrite it.

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • I did exactly that , and after trying to print the matrix , they still didnt freed. Only thing that happened is the first 2 elements on the third rows are now 0 , so I guess thats the only thing that freed . everything is the same – Andrei Dec 01 '16 at 18:33
  • 1
    Time to look at your print routine a bit more carefully. Perhaps it is reading off the end of arrays and causing mayhem. – Michael Dorgan Dec 01 '16 at 18:36
  • @Andrei: even unallocated, the data is still there until another allocation trashes them. – Jean-François Fabre Dec 01 '16 at 18:37