Realloc returns null, why?
hi everyone,
i seem have located orign of bug experiencing.
i think realloc works kind of funky. situation follows:
* allocate buffer of 2 bytes size (malloc)
* reallocate (realloc) same buffer , ask expand size of 4 bytes
* realloc method returns null
this culprit:
pulsebuffer = (unsigned int *)realloc(pulsebuffer , newsize );
but when code follows, 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 missing?
thanks, sander
i seem have located orign of bug experiencing.
i think realloc works kind of funky. situation follows:
* allocate buffer of 2 bytes size (malloc)
* reallocate (realloc) same buffer , ask expand size of 4 bytes
* realloc method returns null
this culprit:
pulsebuffer = (unsigned int *)realloc(pulsebuffer , newsize );
but when code follows, 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 missing?
thanks, sander
sander,
what happens when reduce problem 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 system, both malloc , realloc succeed, printing address 195 each. assuming experiment succeeds you, guess have miscalculated "newsize" somehow. if newsize 4 (print out make sure!), perhaps have consumed of memory (heap) space somewhere , that's why realloc fails.
mikal
what happens when reduce problem 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 system, both malloc , realloc succeed, printing address 195 each. assuming experiment succeeds you, guess have miscalculated "newsize" somehow. if newsize 4 (print out make sure!), perhaps have consumed of memory (heap) space somewhere , that's why realloc fails.
mikal
Arduino Forum > Forum 2005-2010 (read only) > Software > Syntax & Programs > Realloc returns null, why?
arduino
Comments
Post a Comment