Static allocation of opaque data types

前端 未结 9 1075
天涯浪人
天涯浪人 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:36

    You can use the _alloca function. I believe that it's not exactly Standard, but as far as I know, nearly all common compilers implement it. When you use it as a default argument, it allocates off the caller's stack.

    // Header
    typedef struct {} something;
    int get_size();
    something* create_something(void* mem);
    
    // Usage
    handle* ptr = create_something(_alloca(get_size()); // or define a macro.
    
    // Implementation
    int get_size() {
        return sizeof(real_handle_type);
    }
    something* create_something(void* mem) {
        real_type* ptr = (real_type_ptr*)mem;
        // Fill out real_type
        return (something*)mem;
    }
    

    You could also use some kind of object pool semi-heap - if you have a maximum number of currently available objects, then you could allocate all memory for them statically, and just bit-shift for which ones are currently in use.

    #define MAX_OBJECTS 32
    real_type objects[MAX_OBJECTS];
    unsigned int in_use; // Make sure this is large enough
    something* create_something() {
         for(int i = 0; i < MAX_OBJECTS; i++) {
             if (!(in_use & (1 << i))) {
                 in_use &= (1 << i);
                 return &objects[i];
             }
         }
         return NULL;
    }
    

    My bit-shifting is a little off, been a long time since I've done it, but I hope that you get the point.

提交回复
热议问题