new and delete are C++ exclusive keywords so if you are coding in C you have to stick with malloc and free.
I dont know if there is really a difference between using new/delete and malloc/free in C++ but the first pair is easier and cleaner to use, because you dont have to deal with the size of the memory required in the case of classes and structs.
One thing that is very important, is that memory allocated by new and malloc is not necessarily compatible, so you have to check how the memory was allocated before using delete/free. For example, strdup() uses malloc for the duplicated string, so you should use free() in this case.
I dont know if there is really a difference between using new/delete and malloc/free in C++
There is. New/delete handle the construction/destruction of C++ objects, as opposed to the just get/free a block of memory in C. It's not unusual for new/delete to reuse malloc/free under the hood, with perhaps a bit of extra code, but that's not something you deal with. In C++, new/delete it is.
For example, strdup() uses malloc for the duplicated string, so you should use free() in this case.
Correct. But strdup happens to be nonstandard, and besides, in C++, you would be using the STL string class anyway.
new and delete are C++ exclusive keywords so if you are coding in C you have to stick with malloc and free.
I dont know if there is really a difference between using new/delete and malloc/free in C++ but the first pair is easier and cleaner to use, because you dont have to deal with the size of the memory required in the case of classes and structs.
One thing that is very important, is that memory allocated by new and malloc is not necessarily compatible, so you have to check how the memory was allocated before using delete/free. For example, strdup() uses malloc for the duplicated string, so you should use free() in this case.
Hope it helped you and sorry for my english.
Thank you for your answer. Your english was perfect just like your answer :)
Thanks a lot for taking out time and answering my question. Have a great new year!
Comment