Realloc returns null, why?

Hi Everyone,

I finally seem to have located the orign of a bug i was experiencing.
I think realloc works a kind of funky. The situation is as follows:

  • i allocate a buffer of 2 bytes size (malloc)
  • i reallocate (realloc) the same buffer and ask it to expand to a size of 4 bytes
  • the realloc method returns NULL

This is the culprit:
pulsebuffer = (unsigned int *)realloc(pulsebuffer , newsize );

but when i code it as follows, the memory allocation works ok:
unsigned int * prevpulsebuffer = pulsebuffer;
pulsebuffer = (unsigned int *) malloc(newsize);
for (int idx=0;idx<pulsebufferlength;idx++) pulsebuffer[idx] = prevpulsebuffer[idx];
free(prevpulsebuffer);

What am i missing?

thanks, Sander

Sander,

What happens when you reduce the problem to the following simple test case?

void setup()
{
  Serial.begin(9600);
  void *p = malloc(2);
  Serial.println((int)p, HEX);
  p = realloc(p, 4);
  Serial.println((int)p, HEX);
}

void loop()
{}

On my system, both the malloc and the realloc succeed, printing the address 195 for each. Assuming this experiment also succeeds similarly for you, I would guess that you have miscalculated "newsize" somehow. If newsize really is only 4 (print it out to make sure!), then perhaps your have consumed too much of your memory (heap) space somewhere and that's why realloc fails.

Mikal