Static allocation of opaque data types

前端 未结 9 1052
天涯浪人
天涯浪人 2020-11-27 13:50

Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I\'m pretty able to deal with this, but one thing irritates me: it keep

9条回答
  •  春和景丽
    2020-11-27 14:19

    This is an old question, but since it's also biting me, I wanted to provide here a possible answer (which I'm using).

    So here is an example :

    // file.h
    typedef struct { size_t space[3]; } publicType;
    int doSomething(publicType* object);
    
    // file.c
    typedef struct { unsigned var1; int var2; size_t var3; } privateType;
    
    int doSomething(publicType* object)
    {
        privateType* obPtr  = (privateType*) object;
        (...)
    }
    

    Advantages : publicType can be allocated on stack.

    Note that correct underlying type must be selected in order to ensure proper alignment (i.e. don't use char). Note also that sizeof(publicType) >= sizeof(privateType). I suggest a static assert to make sure this condition is always checked. As a final note, if you believe your structure may evolve later on, don't hesitate to make the public type a bit bigger, to keep room for future expansions without breaking ABI.

    Disadvantage : The casting from public to private type can trigger strict aliasing warnings.

    I discovered later on that this method has similarities with struct sockaddr within BSD socket, which meets basically the same problem with strict aliasing warnings.

提交回复
热议问题