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