issue with structs :(

This is a discussion on issue with structs :( within the C++ Programming forums, part of the General Programming Boards category; Hi Following is the code
Code:
struct a{
string k;
int count;
}
a *create()
{
a *b;
b=(a *)malloc(sizeof(a));
...

All malloc does is allocating x bytes of memory. What it doesn't do is actually creating an instance of a particular type. The fact that you have to cast the result to appropriate pointer is a huge give-away.

Therefore it cannot be used for creating objects whose constructor actually does something. In case of your struct the compiler-generated constructor does something, and namely, it calls the default constructor for the string member.

If you want to use malloc, you'll also need to create the object in the returned memory, and this can be done with placement new:

Because the compiler-generated destructor also does something, namely call the destructor of the string member which releases the memory allocated by the string object, you must also remember to call the destructor before freeing the pointer.