I trying to use memcpy to copy content from one array to another, the code is as follow:
#include <stdio.h>
int main(){
int *a;
a = (int*) malloc(sizeof(int) * 4);
a[0] = 4;
a[1] = 3;
a[2] = 2;
a[3] = 1;
int *b;
b = (int*) malloc(sizeof(int) * 4);
memcpy(&b, &a, sizeof(a));
free(a);
for (int i = 0; i < 4; i++){
printf("b[%d]:%d",i,b[i]);
}
printf("%d\n",sizeof(b));
free(b);
return 0;
}
However, when I try to run it, I encounter the following error:
b[0]:4b[1]:3b[2]:2b[3]:18
mem(6131,0x7fffbb4723c0) malloc: *** error for object 0x7fa5a4c02890: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
This error disappear if I remove the free(b)
piece of code, however, I don't know why since I explicitly allocate resource to it.