#define MAGIC_NUM 52571214
void free_mem(void *pMem, int sMem, void **ppMem) {
int iList;
int *magic;
if (pMem == NULL || *ppMem == NULL) {
// Some error message here
return;
}
pMem -= sizeof(*magic);
magic = (int *)pMem;
if (*magic != MAGIC_NUM) {
dbbug("Attempt to recyle invalid memory of size %d.", sMem);
dbbug((char *)pMem + sizeof(*magic), 0);
return;
}
*magic = 0;
sMem += sizeof(*magic);
for (iList = 0; iList < MAX_MEM_LIST; iList++) {
if (sMem <= rgSizeList[iList])
break;
}
if (iList == MAX_MEM_LIST) {
void *array[10];
size_t size;
dbbug("Free_mem: size %d too large.", sMem);
size = backtrace(array, 10);
backtrace_symbols_fd(array, size, STDERR_FILENO);
abort();
}
*((void **)pMem) = rgFreeList[iList];
rgFreeList[iList] = pMem;
*ppMem = NULL; // Added this
return;
}
So, alloc_mem() is crashing when it finds an invalid memory address in its list of recycled memory, but all my calls to alloc_mem() and free_mem() are AFAIK correct. I made sure that strings being freed by free_string() (which calls free_mem()) were originally allocated with str_dup() (which calls alloc_mem()). I'm not mixing alloc_mem() with any other deallocation functions. So why is there an invalid memory address in rgFreeList? :cry:
There are a few calls to malloc() and free() in the code – from what I understand, it is fine to use malloc()/realloc()/calloc() and free() alongside ROM's memory mgmt functions as long as they don't get mixed (malloc() with free_mem(), for example). Am I wrong?
I've had this issue before and was told that it's likely I freed something with free_mem(), that something got added to ROM's recycled list of memory, and somewhere the memory block actually got freed for real, so the address in rgFreeList is bad. It makes sense, but like I said I'm not mixing ROM's alloc functions with C's dealloc functions, so I'm lost…
Has anyone had this problem with ROM? What can I do to figure out what is happening before I go bald? Thank you.