Ngọc Tân Đỗ
Ngọc Tân Đỗ

Reputation: 99

Error Occurs with memcpy

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

Upvotes: 3

Views: 1051

Answers (3)

Adeel Ahmed
Adeel Ahmed

Reputation: 1601

void main()
{
    A *obj=(A*)malloc(sizeof(A));
    obj->a=1;
    obj->b=2;
    Test((void**)obj); //here is the problem

}

you are not passing the address of *obj, you are just casting the (A *) to (void * **),void

main()
{
    A *obj=(A*)malloc(sizeof(A));
    obj->a=1;
    obj->b=2;
    Test(&obj);

}

Memory leak in Test function, 'object' is malloced but not freed neither returned.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

You don't pass the address of the pointer to the function, you pass the pointer itself so *obj in the function is the same as *obj in the main function.

Use the address-of operator to pass a pointer to a pointer:

Test(&obj);

Upvotes: 3

Paul R
Paul R

Reputation: 212929

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.

Upvotes: 6

Related Questions