If you are allocating data for simple (built-in) types (int, float , double, char etc) malloc is fine.
If you are allocating data for structures or classes then it is rather important to use new. The reason for this is that when you use new the constructor for the data type is called where as when you call malloc it is not. Since built in types do not have constructors it is not a problem for them but for classes and structures it can be a serious problem if the constructor is not called.
Couple the fact that newbie programmers forget that a struct and class differ only in the default access specifier for members (public for struct and private for class) and that a class/struct with a default constructor that does nothing can actually be malloc'd without a problem and string is not actually a built-in type but a defined type and a class the following error has occured several times on the board
-
typedef struct mystruct {
-
int someVariable;
-
int someOtherVariable;
-
string str;
-
} MyStruct;
-
-
MyStruct *ms = (MyStruct *)malloc(sizeof(MyStruct));
-
-
ms->str = "Hello World"; // <-- everything falls over
-
string is a class and needs it's constructor called, mallocing MyStruct fails to call the (compiler provided) default constructor of MyStruct so the constructor of str is not called. When the str member is accessed it's internal members have not been initialised correctly and everything falls apart.
Many new C++ programmers seem to thing that string is a built in type but it is in fact extremely import to remember that it isn't.
Also use of typedef and MyStruct in this example is superfluous, C++ automatically defines the structures name mystruct. (I recently went through most of project code at work removing such definitions).