Why does line 190 have a while(true && XXX) ? Just make it while(XXX).
Not related to "malloc v. new" but in numerous places through out this code you make the common newcomer's mistake of using comparison to strlen() to drive a loop. Strlen() requires a variable amount of time to execute, so it should be replaced with a loop that uses a char* (or const char* if the cstring is const) in order to examine each char, like this:
1 2 3 4 5 6 7
|
//This loop is BAD! It works, but it slows things down a LOT...
for(size_t i=0; i < strlen(someStr); ++i)
//Do something with someStr[i]...
//This loop is the best, it goes thru the array only once, while your doing something with the chars.
for(char* cursor=someStr; (*cursor); ++cursor) //Or const char* if someStr is const.
//Do something with (*cursor).
|
Okay, back to malloc v. new: You seem to have the concept and differences right. The real differences are:
1) malloc obtains a number of bytes hence why you need "malloc( numberOfElements*sizeof(Element) )", while new[] gets elements so you only need "new Element[numberOfElements]".
2) malloc has no knowledge of type and returns a void*, so the cast is needed. new[] (and new for that matter) return an Element* so no cast needed.
3) new[] runs the default-constructor on all elements. Singular new can be told to run a non-default c-tor b/c it's obtaining a single element. malloc() leaves the bytes uninitialized and its up to you to initialize each one.
4) Technical: new[] may or may not store meta-data concerning the elements so that the call to delete[] can run the correct number of destructors. malloc() requires you to keep track of the number of elements and manually destroy each element BEFORE calling free() on the pointer.
5) new and new[] throw bad_alloc if they fail to obtain the memory and construct the elements. malloc() returns a nullptr. The only exception to this is if #include <new> is placed at the top of your file and 1 of:
1 2
|
new(std::nothrow) Element; //Counts as a singular new
new(std::nothrow) Element[number]; //Counts as a compound new[] call.
|
those is used. If 1 of those, or malloc(), is used you MUST check that the returned ptr is NOT null before using it!
Point #3 is a non-issue if your using built-in types like int, float, or other pointers, but it becomes a more important issue when using user-created data types.
Malloc() can be useful in some situations, but remember that new/new[] is most often preferable.