Dhruba Jyoti Borah
Dhruba Jyoti Borah

Reputation: 91

How to assign value of a string variable to a string variable of a structure in c++?

I am trying to assign the value of a string variable to another string variable of a structure. But gdb gives an runtime error. The error is as follows: Program received signal SIGSEGV, Segmentation fault. 0xb7f7c8f8 in std::string::assign(std::string const&) () from /usr/lib/i386-linux-gnu/libstdc++.so.6

My C++ program is:

#include<iostream>
#include<stdlib.h>
#include<string>
typedef long unsigned int LUI;
using namespace std;
struct graph {
    string string_node;
    LUI node;
    struct graph *link;
};
struct graph *abc[30];
struct graph *t;
string x;
int main() {
    t = (struct graph *) malloc(sizeof(struct graph *));
    x = "abc";
    t->string_node = x;
    t->link = NULL;
    abc[0] = t;
    cout << "Value is " << abc[0]->string_node << endl;
    cout << "end";

    return 0;
}

Please help me to store the value of x into t->string_node. Thanks in advance..

Upvotes: 0

Views: 140

Answers (2)

jamesdlin
jamesdlin

Reputation: 90115

Your problem is that you're allocating a struct with malloc, but that struct does not have only POD (plain old data) members: it has a std::string member, and std::string objects expect to be constructed. Simply allocating memory for it with malloc will not invoke the std::string constructor, and consequently attempting to interact with that std::string later will result in undefined behavior since that object is in a bad state.

You instead should use new to allocate your struct, and that will properly allocate memory and invoke the default constructor for each member. (Conversely, you should release that memory with delete instead of free to properly invoke the destructor of each member.)

Alternatively, it is possible to use "placement new" to construct an object in memory you've already allocated, but this is not something that you should normally need to do.

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

t = (struct graph *) malloc(sizeof(struct graph *));

graph is a class. It contains C++ classes, specifically it contains a std::string.

All C++ classes must be constructed in dynamic scope using the new operator. They cannot be constructed with the C library function malloc(), which knows absolutely nothing, whatsoever, about C++ classes. Doing so results in undefined behavior (not to mention that your malloc-ed size is wrong, anyway).

Now that you're writing C++ code, you need to completely forget that malloc(), realloc(), and free() ever existed, and always use new and delete.

Upvotes: 2

Related Questions