I tried to use memcpy() function but a error occur:
typedef struct
{
int a;
int b;
}A;
void Test(void **obj)
{
A *object=(A*)malloc(sizeof(A));
memcpy(object,*obj,sizeof(A));//program crash here
printf("a=%d\n",object->a);
printf("b=%d\n",object->b);
free(*obj);
*obj=NULL;
}
void main()
{
A *obj=(A*)malloc(sizeof(A));
obj->a=1;
obj->b=2;
Test((void**)obj);
}
The notification show: "Access violation reading location 0x00000001" When I pass the argument is void* obj. There is not any problem Can anyone help me? Thanks
You have used a typecast to mask a bug in your code. You need to change:
Test((void**)obj);
to:
Test(&obj);
Take-home message: whenever you feel that you need to use a typecast ask yourself why - in the majority of cases it's the wrong solution and will just obscure more serious problems.
Note: you should probably also change:
void Test(void **obj)
to:
void Test(A **obj)
since there is no good reason to use void ** here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With