Dynamic memory allocation issue

Robert S. Grimes rsg at alum.mit.edu
Tue Jan 20 17:55:00 UTC 2009

Torsten Landschoff wrote:
> Robert S. Grimes wrote:
>> I've run across this before, and I've used workarounds, later to find 
>> the problem went away.  I thought it was something I was doing wrong 
>> that I somehow stopped doing, as it didn't happen again for some 
>> weeks/months - until this morning.  I added code like this:
>>   uint8_t* faultTable_;
>>   printk("Getting new fault table of size %d\n", sizeInBytes_);
>>   faultTable_ = new uint8_t(sizeInBytes_);
> Here's the bug. You want to call new uint8_t[sizeInBytes_]
> Note the brackets. What you are doing is to create a single byte on the
> heap, initialized to sizeInBytes_ (in your case 36). But you want 36
> bytes and don't  care for initialization in this case (as you overwrite
> it yourself afterwards).
Of course!  And I know C++ better than that!  But you know how it is - 
sometimes you can't see the trees for all the forest!

And looking back in my revision control system, I had indeed made the 
mistake a year ago, and somehow or other fixed it - after using a 
temporary static array until I really needed to vary it.  When I came 
back to that, I must have noticed the error and fixed it without it 
registering.  Only thing I can say in my defense is that every other 
instance of array allocation I did do correctly - or is that further 
evidence against me?!

Thanks, Torsten!


More information about the users mailing list