replacing malloc with new

Started by
3 comments, last by ekrax 19 years, 8 months ago
hello, i was just going over some code for loading a raw image from one of the nehe tutorials and find that is done in c, so i converted to more c++ type by chaning the typedef in structs, and using streams, and then i needed to change how the memory is allocated ... however i ran into a little problem, with new i must specify a type, but with malloc it seems you get to specify a size ... for example to allocate memory for a raw image is simple ... malloc (width * height * format) ... howver how can i do this with using new? also if i keep the malloc will using delete clear this memory properly or must i use free to do this? thanks for any help. EDIT: just a thought ... would new sizeof (w * h * f) ... work?
Advertisement
well, when using new u say for example:
char * alfa = new char[45] and u got a 45 array o f char.
so u just have to use some 1 byte type and put [width*height*...]. pretty simple
Quote:Original post by ekrax
how can i do this with using new?


typedef char byte;typedef byte* byte_ptr;byte_ptr p = new byte[width * height * format];


Quote:Original post by ekrax
also if i keep the malloc will using delete clear this memory properly or must i use free to do this?


your better off not mixing C memory management facilities with C++'s memory management facilities.

Just need to know that C's memory functions deal with unintialized memory so when you "malloc" no constructor is invoked and when "free" no destructor is invoked but this is okay for just raw bytes of memory like pixels but it doesn't gel well with c++ user-defined types.

EDIT: i may aswell point out if you use malloc with a c++ user-defined type you can invoke the construtor afterwords to initialize using placement new operator, when your done you invoke the destructor expliclity before you call free on the memory, so in the end it isn't really worth it.
If you know how many bytes you need to allocate, you can easily allocate a char array to do this for you.
char* pRawImageData = new char[Width * Height * BytesPerPixel]

Don't forget to delete useing "delete [] pRawImageData;, though. Those brackets are required by the standard when deleting an array, and depending on the compiler, they might also be required by the compiler. (On some compilers you can get away without them, but this isn't recommended practice.)

And no, it's not wise to use delete on pointers that were malloced. If you use new, use delete. If you use new [], use delete []. And if you use malloc, use free.

[edit]Dude, was I ever slow, yet again. This has been happening a lot today.[/edit]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
wow, i sure should have remembered that a char was a byte. thanks for everyones help.

This topic is closed to new replies.

Advertisement