You shouldn't be creating new instances of class P by calling malloc.
Doing so, bypasses the constructor for class P.
This then does not initialize the member string [str] in P.
You should rather be instantiation new instances via the new method as:
P *p1 = new P();
P *p2 = new P();
To utilize malloc to mannualy allocate memory for class P can be done when overiding the new operator. This however, is only useful if you want to allocate memory for an instance of P from a memory pool. When overiding the new operator in such cases, we still have class P's constructor firing.
However, in your case below, if you examine string constructor you may try the floowing hack - this is hwoever not safe and is only listed for purpose of understanding mechanics behind new and malloc abit.