在嵌入式環境中,動態內存本身並沒有什麼問題,但通常它在嵌入式環境中並不會給你帶來太多的收益。
在我看來,它是一個非常好的主意使用環緩衝區(這是一個非常通用的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);
;
這種模式是一個動態可調整大小的緩衝區,具有保證內存使用的功能。當然,其他類型的數據結構(列表,隊列等)也可以用相同的方式實現。
這個:http://www.nongnu.org/avr-libc/user-manual/malloc.html很安靜 – 2009-11-12 23:03:20