RBE
RBE

Reputation: 175

Correct use of memcpy in C

I am attempting to copy the content of an error object from a deque, but when I check the copied content, it is not correct.

typedef struct ER_OBJECT
{
    uint8 error_type;

    union
    {
        uint32 number;
        char *message;
    } error;

} ER_OBJECT;

void er_copy(DE_LIST *deque, ER_OBJECT *object)
{
    ER_OBJECT *marker;

    marker = er_get_first_object(deque);

    memcpy(object, marker, sizeof(*marker));
}

Everything up to and including the function er_get_first_object works as intended, ie I can examine the content of marker and it is correct. This leads me to believe that the problem lies with memcpy.

If I create a second pointer to an ER_OBJECT called marker2, and use memcpy to copy the content of marker into marker2, everything works fine. It is only when I attempt to copy the content of marker to the external object that an error occurs.

Would someone be so kind as to point out what I am doing wrong?

Upvotes: 1

Views: 913

Answers (1)

Dietrich Epp
Dietrich Epp

Reputation: 213797

Unfortunately, the posted code is correct.

I say "unfortunately" because this means that the problem is somewhere else in your program. I suggest using additional tools, such as Mudflap and Valgrind.

  1. If using GCC, compile with -fmudflap. This requires the mudflap libraries to be installed.
  2. Run with Valgrind.

The tools do overlap in purpose somewhat, but there are some errors which only one of the two tools will catch.

Upvotes: 1

Related Questions