954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

String Issue :(

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;
        <strong>tmp->v.name = a2; // CRASHES HERE!!! </strong>
	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

deflamol
Newbie Poster
3 posts since Oct 2008
Reputation Points: 10
Solved Threads: 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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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

deflamol
Newbie Poster
3 posts since Oct 2008
Reputation Points: 10
Solved Threads: 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;

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Worked perfectly !!! :D Thank you so much !!!

deflamol
Newbie Poster
3 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You