0

Hi,

I am having issues with assigning a value to a string. I have two structures node and edge as follows:

struct node{
	string name;
	int key;
};

struct edge
{
	 node u;
	 node v;
	int weight; 
	edge *link; 
}*front = NULL;

Now I have a function that I am using to create a priority queue to order edges according to their weights, however whenever I try to assign a value to a name attribute of a node the program crashes:

void insert_pque(string a1, string a2, int i,int j,int wt) 
{
	edge *tmp,*q;
	tmp = (edge *)malloc(sizeof(edge)); 

	tmp->u.key=i;
        [B]tmp->v.name = a2; // CRASHES HERE!!! [/B]
	tmp->v.key=j; 
	tmp->weight = wt; 
...
}

When debugging crash message from memcpy.asm:

TrailUp1:
        mov     al,[esi]        ;U - get byte from source
                                ;V - spare
        mov     [edi],al        ;U - put byte in destination
        mov     eax,[dst]       ;V - return pointer to destination
        pop     esi             ;U - restore esi
        pop     edi             ;V - restore edi
        M_EXIT

When I use simple char as type for the name everything works fine, however when I try using strings it crashes ! :(

Any help would be much appreciated,
Thanks

Deflamol

2
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by deflamol
0

You can't use malloc() to allocate c++ objects like std::string, but use the new operator. This is more than likely the cause of your program crashing.

0

Thank you for the reply Ancient Dragon,

Unfortunately I'm not sure on how to do that :

I tried doing this:

tmp->u.name = new string ();

But it didn't work... Any hints?

Again thank you very much

0

you don't specifically allocate memory for the string object because it is not a pointer inside the structure. Just allocate tmp and everything will be allocated ok tmp = new edge;

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.