Search code examples
cpointersstructnullfree

After sending a pointer to an external function to make it null, it doesn't change to null


I have created a pointer of type "Vector" (see code). After creation I want to send a pointer of type Vector (meaning Vector*) to a function called "VectorDestroy(Vector* _vector), which frees the struct from memory and assigns it to null. However when I continue in the code and want to test if the returned vector is null it fails; meaning it is not changed to null

This is the struct:

struct vector
{
    int* m_items;
    size_t m_originalSize; /*original allocated space for items*/
    size_t m_size; /*actual allocated space for items*/
    size_t m_nItems; /*actual number of items*/
    size_t m_blockSize; /*the chunk size to be allocated when no space available*/
    int m_magicNumber;

};

typedef struct vector Vector;

This is the external function VectorDestroy which is found in module1:

void VectorDestroy(Vector* _vector)
{   
    if(_vector == NULL || _vector->m_magicNumber != MAGIC_NUMBER)
    {
        return;
    }

    _vector->m_magicNumber = 0Xdeadbeef;
    free(_vector->m_items);
    _vector->m_items = NULL;
    free(_vector);
    _vector = NULL;
}

This is the test function which is found in module2:

int VectorDestroyFunctional()
{
    Vector* vector = VectorCreate(5, 5);

    if(vector == NULL)
    {
        PrintResult(FAIL);
        return FAIL;
    }

    VectorDestroy(vector);

    if(vector == NULL)
    {
        PrintResult(PASS);
        return PASS;
    }

    PrintResult(FAIL);
    return FAIL;
}

After the free() function in VectorDestroy and assigning the pointer to null I expected the pointer to be null and the test would pass, but in debugging I found out the pointer is not set to null and the test fails. Am I missing something?


Solution

  • You nullified the local copy of the pointer. To nullify the pointer in the calling code, you'd need to pass a pointer to a pointer to the function:

    void VectorDestroy(Vector **p_vector)
    {   
        if (p_vector == NULL || *p_vector == NULL)
            return;
        Vector *vector = *p_vector;
        if (vector->m_magicNumber != MAGIC_NUMBER)
            return;
    
        vector->m_magicNumber = 0Xdeadbeef;
        free(vector->m_items);
        vector->m_items = NULL;
        free(vector);
        *p_vector = NULL;
    }
    

    and you'd call:

    VectorDestroy(&vector);