Agirl
Agirl

Reputation: 45

Deep copy of struct in C

I have the following structs, and need to make a deep copy of state into newState.

typedef struct statestruct{
    int instrMem[100];
    IDTType ID;
    int cycles;
} stateType;

typedef struct ID{
    int val;
} IDType;

Assuming that state is already initialized, why doesn't the following code work? It appears that it is only doing a shallow copy, and I can't change the val inside newState without it changing in state.

newState = (stateType*)malloc(sizeof(stateType));
newState = state;
memcpy(&(newState->ID), &(state->ID), sizeof(IDType));

Upvotes: 1

Views: 3479

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You are reserving space for the pointer in:

newState = (stateType*)malloc(sizeof(stateType)); /* Don't cast malloc */

but in the next line, you overwrite the address returned by malloc (memory leak):

newState = state;

If you want to copy the contents of where state points, just use:

newState = malloc(sizeof(stateType));
*newState = *state; /* Dereference to access the contents */

This line doesn't make sense:

memcpy(&(newState->ID), &(state->ID), sizeof(IDType));

because this member (ID) is already copied when you assign using =

Upvotes: 3

Related Questions