Pages: [1]   Go Down
Author Topic: Realloc returns null, why?  (Read 1715 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Karma: 0
Posts: 4
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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];

What am i missing?

thanks, Sander
« Last Edit: August 23, 2008, 12:41:16 pm by SanderS » Logged

Austin, TX USA
Offline Offline
God Member
Karma: 5
Posts: 997
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


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

void setup()
  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.


Pages: [1]   Go Up
Jump to: