Skip to content

Add static allocation only option #2

@petervaro

Description

@petervaro

The FW uses new => ini => fin => del method-sequences to create new instances, so it is possible, to inherit/composit child-types easily. But this approach is also a reasonable candidate to make it possible to use the whole FW as a statically allocated one by calling only ini and fin on the statically allocated objects.

However right now, several dynamic allcoations are going on in the ini and the fin methods of some of the types. Whenever this is the case, the ini and the fin functions should accept as many pointers as the number of mallocs they have. For example, if the current ini is something like this:

typedef struct
{
    /* members */
} Container;

typedef struct
{
    Container *container;
} Type;

Error
Type_ini(Type *const self)
{
    if (!self)
        return SELF_IS_NULL;

    if (!(self->container = malloc(sizeof(Container))))
        return ALLOC_FAIL;

    retrun OKAY;
}

then it should be refactored as follows:

Error
Type_ini(Type      *const self,
         Container *const container)
{
    if (!self)
        return SELF_IS_NULL;

    if (container)
        self->container = container;
    else if (!(self->container = malloc(sizeof(Container))))
        return ALLOC_FAIL;

    return OKAY;
}

Also, if the current implementation of fin is like:

Error
Type_fin(Type *const self)
{
    if (!self)
        return SELF_IS_NULL;

    free(self->container);

    return OKAY;
}

then it should be rewritten as follows:

Error
Type_fin(Type      *const self,
         Container *const container)
{
    if (!self)
        return SELF_IS_NULL;

    if (!container)
        free(self->container);

    return OKAY;
}

This approach also makes it possible to select which members should be dynamically al;located and which is statically. After this small improvement, both of the following use-cases of the types would be valid:

Container  c;
Type       t_static,
          *t_dynamic ;

Type_new(&t_dynamic);
Type_del(&t_dynamic);

Type_ini(&t_static, c);
Type_fin(&t_static, c);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions