Search code examples
cmemory-managementmalloccalloc

Correct memory allocation for a struct


Having a struct defined in a such way, I need to allocate memory

typedef struct string_collection {
    char **c;
    size_t current, allocated;
} TSC, *ASC;

So I came with this code, is it right or I missed something? First allocating struct descriptor and then enough space for d pointers to string

ASC AlocSC(size_t d)
{
    ASC sc;

    sc = (TSC*) malloc(sizeof(TSC));
    if (!sc) return NULL;

    sc->c = calloc(d, sizeof(char *));

    if (!sc->c) {
        free(sc);
        return NULL;
    }

    sc->current = 0;
    sc->allocated = d;

    return sc;
}

Solution

  • The code as edited is essentially correct, though I have several stylistic differences with you (such as not doing a typedef to hide the "pointerness" of an object, not using the size of the allocated object in the malloc/calloc call, and a few other things).

    Your code, "cleaned up" a bit:

    TSC *AlocSC(size_t d)
    {
        TSC *sc = malloc(sizeof *sc);
        if (!sc) return NULL;
    
        sc->c = calloc(d, sizeof *sc->c);
        if (!sc->c) {
            free(sc);
            return NULL;
        }
    
        sc->current = 0;
        sc->allocated = d;
    
        return sc;
    }