Search code examples
cpointersmallocbinary-treefree

Creating a deep copy of a binary tree containing other structures in C


I have this function that's supposed to create a deep copy of a whole binary tree.

symbol_t* cloneTable(symbol_t *node) {

    if (node == NULL)
        return node;

    symbol_t *newSymbol = malloc(sizeof(symbol_t));
    newSymbol->type = node->type;
    newSymbol->key = node->key;

    if (node->value != NULL) {
        value_t *newValue = malloc(sizeof(value_t));
        newValue = node->value;
        newSymbol->value = newValue;
    }

    newSymbol->leftChild = cloneTable(node->leftChild);
    newSymbol->rightChild = cloneTable(node->rightChild);

    return newSymbol;
}

When I change value in the original table, it gets changed in the copied table, too, however.

What can I do to create a deep copy of it?

Thank you in advance for any help.


Solution

  • In:

        value_t *newValue = malloc(sizeof(value_t));
    

    you allocate memory for an object. As it looks, node contains a pointer to a value object. With

        newValue = node->value;
    

    you copy the pointer. To copy the value, use:

        *newValue = *node->value;
    

    Now you can place the object in your new node:

        newSymbol->value = newValue;
    

    N.b.: Don't forget to set newSymbol->value= NULL; when node->value==NULL