嵌入式环境中的动态内存本身并没有什么问题,尽管在嵌入式环境中它通常不会给你带来太多好处。
在我看来,使用环形缓冲区是一个非常好的主意(这是 I/O 驱动程序等非常常见的数据结构)。这样,如果由于某种原因您无法为队列提供服务,内存使用仍然是确定性的。
使用一些宏可以在编译时分配可变大小的结构。
例如 -
//we exploit the fact that C doesn't check array indices to allow dynamic alloc of this struct
typedef struct ring_buf_t {
int element_sz,
buffer_sz,
head,
tail;
char data[0];
} ring_buf_t;
#define RING_BUF_ALLOC_SZ(element_sz,n_elements) (sizeof (ring_buf_t) + \
(element_sz) * (n_elements))
char backing_buf[RING_BUF_ALLOC_SZ (sizeof(type_to_buffer), 16)];
//ring_buf_init() casts backing buf ring_buf_t and initialises members...
ring_buf_t *ring_buffer = ring_buf_init (element_sz, n_elemements, backing_buf);
;
这种模式是一个动态大小的缓冲区,具有保证的内存使用。当然,其他类型的数据结构(列表、队列等)也可以以相同的方式实现。