Memory Allocation: new vs. malloc vs. ?
-
Thanks to all that helped me get over my debug issues... It turns out (as many suggested) that the code I was porting from 'c' and wrapping in an MFC gui had to lose all the old malloc/reallocs it had to work correctly without causing debug to puke. This manifested itself in strings for the most part. From what several said, malloc uses a different stack than new, and was causing one to stomp on the other. I must ask at this point...why? Is there a "safe" wrapper out there for malloc (to possibly save re-writing old code)? why did only debug have a problem with sharing methods? Based on call stacks examined while getting to the bottom of this, I saw CString using malloc and free deep down inside... why don't these cause issues? Thanks again
-
Thanks to all that helped me get over my debug issues... It turns out (as many suggested) that the code I was porting from 'c' and wrapping in an MFC gui had to lose all the old malloc/reallocs it had to work correctly without causing debug to puke. This manifested itself in strings for the most part. From what several said, malloc uses a different stack than new, and was causing one to stomp on the other. I must ask at this point...why? Is there a "safe" wrapper out there for malloc (to possibly save re-writing old code)? why did only debug have a problem with sharing methods? Based on call stacks examined while getting to the bottom of this, I saw CString using malloc and free deep down inside... why don't these cause issues? Thanks again
new and delete call malloc/free internally, I believe, but if you're writing C++, the rule is to use new/delete. Apart from anything else, it gives you constructor/destructor behaviour.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog
-
Thanks to all that helped me get over my debug issues... It turns out (as many suggested) that the code I was porting from 'c' and wrapping in an MFC gui had to lose all the old malloc/reallocs it had to work correctly without causing debug to puke. This manifested itself in strings for the most part. From what several said, malloc uses a different stack than new, and was causing one to stomp on the other. I must ask at this point...why? Is there a "safe" wrapper out there for malloc (to possibly save re-writing old code)? why did only debug have a problem with sharing methods? Based on call stacks examined while getting to the bottom of this, I saw CString using malloc and free deep down inside... why don't these cause issues? Thanks again
The key is if you use
malloc
/realloc
to allocate memory you usefree
to deallocate the memory. If you usenew
to allocate memory you usedelete
to deallocate it. When I port code from C, I don't bother changing the malloc's. There's no point and it often causes more bugs than just leaving the mallocs/frees alone.Anyone who thinks he has a better idea of what's good for people than people do is a swine. - P.J. O'Rourke