Search code examples
carrayspointersmallocrealloc

C - Dynamically sized array of struct pointers without using realloc?


I need help with a school assignment, specifically with resizing the amount of memory allocated for a pointer WITHOUT realloc.

I have the following declarations in my program.

struct GraphicElement
{
    enum{ SIZE = 256 };
    unsigned int numLines;
    Line* pLines;
    char name[SIZE];
};

typedef struct 
{
    unsigned int numGraphicElements;
    GraphicElement* pElements;
}VectorGraphic;

VectorGraphic Image;

As the program runs I'll be adding more GraphicElements to pElements.

For example, after 5 iterations the memory for pElements should be something like this:

[GraphicElement 0][GraphicElement 1] ... [GraphicElement 4]


For the function AddGraphicElement(VectorGraphic* vg) I have this code (with some lines removed for easier reading):

vg->pElements = (GraphicElement*)realloc(vg->pElements, sizeof(GraphicElement)*(vg->numGraphicElements+1));

//Then I assign inputs from user into the members of the struct at vg->pElements[vg->numGraphicElements]

vg->numGraphicElements++;

This works, BUT according to the instructions given by my professor, I'm only allowed to use malloc and free- no realloc. Sadly the only way I've made this work is with realloc.

Can anyone point me in the right direction to implement this using only malloc?

Thanks!


Solution

  • If you are not allowed to use realloc, but malloc and free are allowed, you can replace the call with the following, less efficient, sequence:

    void *newData = malloc(newSize);
    memcpy(newData, oldData, oldSize);
    free(oldData);
    

    Internally, realloc does the same thing, but it does so more efficiently. Unlike user program, realloc knows the actual size of the dynamic memory chunk, so it checks if newSize <= actualSize to avoid reallocation. When actualSize is insufficient, realloc does the same thing as above. realloc has additional logic to deal with situations when the size need to shrink, but in your situation this does not apply.