Neil Palmer

malloc() confusion

Discussion created by Neil Palmer on Jun 12, 2008
Latest reply on Jun 12, 2008 by Neil Palmer
Hi all.
I hope someone can explain to me why this happens. I was having weird behaviour with malloc in a project, so I wrote a simple test program to play with malloc and I found a strange problem. (see code below). In the first loop, nothing is previously allocated, and every attempt at malloc() passes (does not return NULL). The I make an allocation from the heap with pBlock = malloc(8); and re-run the test loop. Now, most of the attempts at malloc fail, with only 8 passes while z is in the range of 5 to 12. Can anyone explain to me why this is happening.

I am using Codewarrior development studio for Coldfire, special edition V7.0 build 15


//#include <stdlib.h>/*Including used modules for compiling procedure*/#include "Cpu.h"/*Include shared modules, which are used for whole project*/#include "PE_Types.h"#include "PE_Error.h"#include "PE_Const.h"#include "IO_Map.h"uint8* pTest;uint8* pBlock;uint8 x,y,z,a;uint16 pass,fail;void main(void){  /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/  PE_low_level_init();  /*** End of Processor Expert internal initialization.                    ***/x=0;y=0;pass = 0;fail = 0;//// Here, nothing is already allocated//for(z=1; z<250; z++) { pTest = malloc(z); if(pTest == NULL)  ++fail; else  {  ++pass;  free(pTest);  } } //Here, every attemp at malloc passedpBlock = malloc(8); //Here, we allocate another block of heappass=0;fail=0; for(z=1; z<250; z++) { pTest = malloc(z); if(pTest == NULL)  ++fail; else  {  ++pass;  free(pTest);  } }  for(;;) {}} //Here, we only had 8 attempts at malloc pass, whith z = 5-12  //The rest of the attempts failed./* END Project */