0

I want to call a function that uses my 2d dynamic array to create another 2d dynamic array and then rewrite the value for my first array. So the code is something like this:

#include <stdio.h>
#include <stdlib.h>

int **bigger(int **A)
{
    int i;
    int **A2 = (int **)malloc(10 * sizeof(int *));

    for(i = 0; i < 10; i++)
        A2[i] = (int *)malloc(10 * sizeof(int));

    return A2; 
    }

int main(void)
{
    int i;
    int **A = (int **)malloc(5 * sizeof(int *));

    for(i = 0; i < 5; i++)
        A[i] = (int *)malloc(5 * sizeof(int));

    A = bigger(A);

    for(i = 0; i < 10; i++)
        free(A[i]);

    free(A);

    return 0;
}

If I check it with valgrind --leak-check=yes I get total heap usage: 6 allocs, 3 frees, 240 bytes allocated. How can I solve this memory leak ?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

4

TL:DR, you're not re-writing, you're overwriting.

The problem is in

 A = bigger(A);

inside bigger() function, you're allocating new memories and then, storing the same back into A, which makes you lose the pointer to previously allocated memories, thus rendering them unreachable and are not free()-d. Those causes the leak here.

You need to use realloc() for resizing already malloc()ed memory regions.

Otherwise, before you call malloc() again, inside the bigger(), you ought to free() the available memories.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • But how do i solve the problem if i need another copy of the original array in my function, let's say A and A2, i do my tasks and then i return A2 ? – Mihai Podaru Dec 02 '16 at 07:55