我已经搜索了几天,但没有找到答案。
堆内存碎片化是使用malloc()和free()在微控制器/Arduino中的结果。
如果无法避免使用它们,如何定期进行碎片整理以确保下一个malloc()调用将找到连续的内存来分配?
我已经搜索了几天,但没有找到答案。
堆内存碎片化是使用malloc()和free()在微控制器/Arduino中的结果。
如果无法避免使用它们,如何定期进行碎片整理以确保下一个malloc()调用将找到连续的内存来分配?
正如@kkrambo所提到的,使用队列或链表来跟踪分配的内存块。我已经提供了一个针对Arduino的示例,该示例没有我想要的所有功能。
我选择仅在队列中保留指向内存块的指针,而不是块本身(尽管我不知道他/她是否意味着我上面所说的内容)。
const int MAX_POOL_SIZE = 4;
const int MAX_DATA_SIZE = 128;
// Memory pool for data
QueueArray <uint8_t*> dataPool;
void initDataPool () {
uint8_t * ptr;
for (int i = 0; i < MAX_POOL_SIZE; i++) {
ptr = (uint8_t*) malloc(MAX_DATA_SIZE); // Allocate MAX_DATA_SIZE buffer
dataPool.push(ptr); // Push buffer pointer to queue
}
}
// Allocate message data buffer from data pool
// If data pool still has buffer space available, and requested
// buffer size is suitable, return pointer to avalable buffer
static void* allocateDataBuff (size_t buffSize) {
if (!dataPool.isEmpty()) {
if (buffSize < MAX_DATA_SIZE) return dataPool.pop();
else {
if (debugMsg) Serial.println("allocateDataBuff: Requested Buffer Size is too large");
return NULL;
}
} // if message pool still has buffer space available
else {
if (debugMsg) Serial.println("allocateDataBuff: Memory pool is full, no buffers available at this time");
}
}
void setup() {
initDataPool();
}
void loop() {
// ........
uint8_t* dataPtr = (uint8_t*) allocateDataBuff(100);
// ....assign message to *dataPtr
// ........
deallocateDataBuff(dataPtr);
}