precision
precision

Reputation: 303

How to avoid memory leak where function returning an array

In the following code pointer A had different address before calling the function copy(). Once the copy() is executed, pointer A got the address of pointer B which is declared in copy(). So, within main() when free(A) is executed, it's freeing the memory assigned to the pointer B in copy(). Now the problem is how to deallocate pointer A assigned within main() ? Is there any memory leaks in the following code? How to prevent it?

Here is the code:

#define size 10
int *copy(int *A){
int i;
int *B = (int *)calloc(size,sizeof(int));
printf("address of B=%p\n",B);
for(i=0;i<size;i++){
       B[i]=A[i]+1;
    }
for(i=0;i<size;i++){
   printf("%d ",B[i]);
   }
 printf("\n ");
 return B;
 }

 int main(){
     int i;
     int *A = (int *)calloc(size,sizeof(int));
     printf("address of A before copy()=%p\n",A);

     for(i=0;i<size;i++){
        A[i] = i;
        }
        A=copy(A);
      printf("address of A after copy()=%p\n",A);
     for(i=0;i<size;i++){
         printf("%d ",A[i]);    
         }
     printf("\n");
     free(A);
     return 0;
     }

And here is the output:

   address of A before copy()=0x1e64010
   address of B=0x1e64040
   1 2 3 4 5 6 7 8 9 10 
   address of A after copy()=0x1e64040
   1 2 3 4 5 6 7 8 9 10 

Upvotes: 1

Views: 312

Answers (1)

tdao
tdao

Reputation: 17678

Is there any memory leaks in the following code?

Yes, there's potentially a memory leak from these lines:

int *A = (int *)calloc(size,sizeof(int));

int *A = copy(A);   // <-- Do NOT allocate and then point the pointer to somewhere else

That is because you allocated memory for A, and then you pointed A to somewhere else, thus loosing the handle to free the memory initially allocated.

NOTE:

  • In this particular case, though, you might get away with it because it happened in main() - and the memory could be deallocated by the OS itself when the program exits.
  • Generally speaking, however, this kind of code would cause memory leak, especially when the function is not main(). Also, it's a bad practice leaving it the OS to do the clean up for you.

how to deallocate pointer A assigned within main() ?

How to make it works - here's a suggestion:

  • Declare a 2nd pointer B within main()
  • Then call copy to copy/modify content from original array.

The code should look like this:

 int *A = (int *)calloc(size,sizeof(int));

 // Initialize A
 for( i=0;i<size;i++ )
 {
    A[i] = i;
 }

 // Copy A to B, and modify the content.
 int *B = copy(A);   // <-- 2nd pointer

And at the end, free both pointers:

free( A );
free( B );

Upvotes: 4

Related Questions