简体   繁体   中英

copying a string in C++ "Error reading characters of string."

I am implementing a stack and I would like to push and pop string data. can I not just set

string name = originalString ???

here is what I have for push:

void push(StackNode** top_ref, int nAttack, int nDefense, string nName, string nType) {
    StackNode* stackNode = (StackNode*)malloc(sizeof(StackNode));
    stackNode->attack = nAttack;
    stackNode->defense = nDefense;

    stackNode->name = nName; //not working
    stackNode->type = nType; //not working

    stackNode->next = NULL;
    stackNode->next = *top_ref;
    *top_ref = stackNode;
} 

where stackNode->name

and stackNode->type is already defind as a string

I keep getting: "Error reading characters of string."

The issue is malloc doesn't play well with objects. See Does malloc create a new instance of the class or not?

malloc allocates enough space to hold a StackNode , but doesn't call the constructor on it. Nor does it create the underlying member objects, your string s included. To do so, you need to do like described in this answer:

A* a = (A*)malloc(sizeof(A));
new (a) A();

a->~A();
free(a);

But at this point, you really should just be using new anyway. There's very little reason to use new in C++ (there's a time and a place, but minimize it). There's even fewer times when it's right to call malloc .

Do

StackNode* stackNode = new StackNode;

which will call the constructor appropriately. Remember to call delete on the memory when you're done with it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM