Dear All,
I am developing with a flexis QE64 with Codewarrior v5.9.0 build 2404 and I experienced some problems with realloc function.
I am using the pre defined function in ALLOC.C (path \CodeWarrior for Microcontrollers V6.1\lib\hc08c\src) and there are some conditions where the reallocation fails.
Either using mutilink P&E or full chip simulation, the following code fails:
In the following piece of code the block where I request a reallocation is 15 bytes and when I call the function realloc((void*) ptr13, 22); the new block is only 5 bytes.
void main(void) {
unsigned char *ptr1, *ptr2, *ptr3, *ptr4, *ptr5, *ptr6, *ptr7, *ptr8, *ptr9, *ptr10, *ptr11, *ptr12, *ptr13, *ptr14;
unsigned char i;
EnableInterrupts; /* enable interrupts */
/* include your code here */
// Build an Heap
ptr1 = malloc(4 * 5 - 5);
ptr2 = malloc(7 * 5 - 5);
ptr3 = malloc(4 * 5 - 5);
ptr4 = malloc(4 * 5 - 5);
ptr5 = malloc(3 * 5 - 5);
ptr6 = malloc(4 * 5 - 5);
ptr7 = malloc(5 * 5 - 5);
ptr8 = malloc(7 * 5 - 5);
ptr9 = malloc(7 * 5 - 5);
ptr10 = malloc(3 * 5 - 5);
ptr11 = malloc(9 * 5 - 5);
ptr12 = malloc(14 * 5 - 5);
ptr13 = malloc(5 * 5 - 5);
ptr14 = malloc(7 * 5 - 5);
free(ptr4);
ptr4 = malloc(3 * 5 - 5);
free(ptr13);
ptr13 = malloc(4 * 5 - 5);
free(ptr12);
// fill the space
for(i = 0; i < 15; i++){
*(ptr13 + i) = i + 1;
}
realloc((void*) ptr13, 22);
__RESET_WATCHDOG(); /* feeds the dog */
} /* loop forever */
Can someone help me?
Thanks in advance.
Using the full chip simulation tool in Codewarrior I saw, at the end of reallocation, that at the returned address (the realloc returned address) there was only 1 2 3 4 5 and then another heap header block started.
Attached you can find two pictures with the heap status before and after the realloc call.
Note that ptr13 = 0x026E (the block where the realloc has been called) and dest = 0x0228 (the returned block).
If you want I can give to you the all project.
For Lundin:
The realloc function returns the pointer of the new re-allocated block. From the return point of view the reallocation succeeded but the size of the reallocated block is only 5 and not 22 (or 25) as requested.
For CrasyCat:
The realloc has been called with a valid block pointer, the area has not been freed!
Thanks.
Hello
I did check the ANSI C standard and I found that
"
If ptr does not match a pointer earlier returned by calloc, malloc, or realloc, or if the space has been deallocated by a call to free or realloc, the behaviour is undefined"
May be you should not free the memory block first.
CrasyCat