Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Occurs with memcpy

Tags:

c

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

like image 572
Ngọc Tân Đỗ Avatar asked Mar 06 '26 17:03

Ngọc Tân Đỗ


1 Answers

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.

like image 94
Paul R Avatar answered Mar 09 '26 07:03

Paul R