Sometimes knowledge of using
malloc, for allocating memory in common and less complicated situations, can prove wrong in complicated situations.
Situation  (Complication Level 1):
int *pData = (int*)malloc(10 * sizeof(int));
Now to access integers at index from 0 to 9 simply use
Situation  (Complication Level 2):
ABC *pData = (ABC*)malloc(10 * sizeof(ABC));
Now to access integer P1 of say 4th struct ABC :
Again Very simple!!!
Situation  (Complication Level 3):
PQR *pData = (PQR*)malloc(10 * sizeof(PQR));
Now to access integer P1 of ABC which is inside of say 5th struct PQR :
Again Moderately simple!!!
In above 3 situations memory was allocated and then utilized according to the structure\ layout of structs.
Situation  (Complication Level 4):
XYZ *pData = (XYZ*)malloc(10 * sizeof(XYZ));
Now try to insert elements in the list P3 of say 4th struct XYZ:
pData.P3.AddTail(2);Complie Status OK.
Run Status CRASH!!!
Without reading further think a minute why the code did not worked even though memory was already allocated?
This happened because though memory was allocated for all the data members of list
XYZ::P3but those data members were not initialized with default values.
struct XYZin above example is composite data type (a class or user defined data type) in which the default value initialization of its data-members is normally done in constructor of the class.
In a composite data type the data-members are created (here created means calling of their respective constructor) prior to the invocation of composite data type constructor itself. ("Refer how Object creation takes place")
So what will initialize the data-members along with the task of allocating the memory for members.
XYZ *pData = new XYZ;
Here 'new' invokes the constructor of both, the data members of
struct XYZand the
struct XYZitself. Inside the
Anyway, in C++
newis the preferred mechanism for memory allocation.
Also try to minimize mixing of