Mariah
Mariah

Reputation: 111

Initialising struct through a function whose members are dynamic arrays

I have the following struct definition (names have been generalised):

typedef struct structure{
    int *array1;
    int *array2;
} structure_t;

I need to initialise this struct data structure through a function which takes in the sizes of the two arrays as parameters. The function returns a pointer to that data structure and NULL on fail.

I am getting confused on how to go about this. I know that I cannot return a pointer of a locally declared struct, and I also know that I need to dynamically allocate memory for the two members array1 and array2, since the size is not known on compile time (it's inputted by this user). I have tried the following:

structure_t* init(int size1, int size2)
{
    structure_t *st = malloc(sizeof (structure_t));

    if(st == NULL) return NULL;

    st->array1 = malloc((sizeof (int))*size1);
    st->array2 = malloc((sizeof (int))*size2);

    return st;
}

I have checked and everything is being initialised. But then when I come to free the memory it is not working properly, as only the pointer to array1 is being changed to NULL.

bool destroy(strcuture_t *st)
{
    free(st->array1);
    free(st->array2);
    free(st);

    if (st == NULL)
        return true;
    else
        return false;
}

What am I doing wrong?

Upvotes: 2

Views: 61

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222763

free does not change the value of the pointer passed to it. It cannot, as it receives only the value and not a reference to the pointer.

To record that a pointer no longer points to valid memory, you can set the pointer to NULL yourself after calling free, as with:

free(st);
st = NULL;

Further, once the memory pointed to by st is freed, the C standard does not define the behavior of accessing st->array1 or st->array2 or even of using the value of st at all. There is no reason to expect that checking st->array1 or st->array2 for a null pointer will produce any particular result. The comparison may evaluate to true, may evaluate to false, may cause your program to abort, or may cause your program to misbehave in other ways.

Upvotes: 1

Related Questions