cannot assign value to std::string

Hi,

I have problem. Take a look at my code:

struct myStruct{
std::string sTest;
bool bGrab;
};

myStruct *ptrStruct;

//allocate memory
if ((ptrStruct = (myStruct *)malloc(sizeof(myStruct) * (numMasterModel))) == NULL)
exit (-1);

//assign value
ptrStruct->sTest = "just test" //<-- GENERATE RUNTIME ERROR !
strcpy( ptrStruct->sTest, "just test") //<-- ALSO GENERATE RUNTIME ERROR !
ptrStruct->sTest.assign( "just test" )//<-- ALSO GENERATE RUNTIME ERROR !

How to solve this problem? I'm using Microsoft Visual C++. NET 2003. Compiler points to file "iosfwd" when error rises. Please help me.

And my last question, what is the different between this code:

struct myStruct{
std::string sTest;
bool bGrab;
};

and this code:

typedef struct{
std::string sTest;
bool bGrab;
} myStruct;

Thank you.
Last edited on
You should not use malloc when variables of classes are involved.
The structure contains a variable of type string. Malloc just allocates the memory requested and this memory is UNINITIALED - so the string variable is just garbage - it not a real variable of type string at all.
Malloc can be used where intrinsic types like ints, chars, pointers, structures (without embedded class variables) etc.

You should use the new and deletefunctions in C++
NOT malloc and free


NOTE: that if you had used a pointer to std::string rather than a string variable then you could do like below;
1
2
3
4
5
6
7
8
9
10
struct myStruct{
std::string *sTest;
bool bGrab;
};

myStruct *ptrStruct;
  
ptrStruct =  (myStruct*)malloc(sizeof(myStruct));
ptrStruct->sTest=new std::string();
  


But this mixes malloc and new..
There is nothing wrong with using both malloc() and new in the same program.

But it is an abomination to use free() with new or delete with malloc().

Guestgulkan makes very good points. If you were to use malloc() on an object type, you would have to explicitly construct it, and later you'd have to explicitly destruct it before free()ing it. Likewise, when programmers see the perfectly good and working code he posted as a bad example, the reason C++ programmers will cringe at it is that it is not using dynamic memory in a consistent way.

In general, use new and delete in new code you write, unless you are required to use malloc() and free() due to legacy interfaces or code or libraries or whatever. new and delete provide type-safety and a whole host of other benefits and have no disadvantages over the older C memory functions.

:-)
Last edited on
Topic archived. No new replies allowed.