Search code examples
carraysstructmallocrealloc

How should I malloc/realloc with a struct that includes an array?


I'm pretty new to c, so if my steps are wrong, please let me know. Let's say that I have something like the following:

struct graphNode{
    int val;
    graphNode* parent;
    int succSize;
    int succMaxSize;
    graphNode* succ[1];
};

I will create a new node with:

graphNode *n;
n = malloc(sizeof(struct graphNode));
assert(n);
n->val = 1;
n->parent = NULL;
n->succSize = 0;
n->succMaxSize = 1;

Then, if I want to add a successor to the node

if (n->succSize == n->succMaxSize){
    n->succ = realloc(n->succ, sizeof(graphNode*) * n->succMaxSize * 2);
    n->succMaxSize *= 2;
} 
n->succ[succSize] = n2; //n2 is of type graphNode*
succSize++;

Is this correct? Do I need to realloc for the struct as well or is realloc of the array enough? Do I need to malloc for the initial array? Should the initial array size be included in my malloc call for n?


Solution

  • The usual way to define a "stretchy" array member in C is to either specify a size of 0 or no size at all, e.g.:

    struct foo {
        int stuff;
        bar theBars[]; // or theBars[0]
    };
    

    With this definition, sizeof(struct foo) will include all the elements other than the array at the end, and you can allocate the right size by saying malloc(sizeof(struct foo) + numberOfBars * sizeof(bar)).

    If you need to reallocate it to change the number of bar elements, then you'll use the same formula (but with a new numberOfBars).

    To be clear, you can't just realloc part of a struct. You have to realloc the whole thing.