Why does sending a string to a structure fail?

I have a structure that contains, among other things, a couple of lines.

struct item { string item_name; int item_property_1; double item_property_2; } 

Later I initialize them:

 item item1; item1.item_name = "Name of Item"; item1.item_property_1 = 5; item1.item_property_2 = 10.0; 

If I comment on the line that assigns the line, it works fine. When a line is assigned, it will work. I have no idea why.

Now I have commented on the contents of every other function, trying to track what might cause the alleged damage, and it still crashes. I got to one structure with several lines and numbers, and if I assign a value to any of the lines, it will work.

What could lead to this corruption?

edit Adding, upon request, the least amount of real code that causes a crash. Commented sections are omitted.

 struct player_c { string advClass; int role; }; player_c shadow; Shadow::Shadow(QWidget *parent) : QMainWindow(parent), ui(new Ui::Shadow) { ui->setupUi(this); shadow.advClass = " "; shadow.role = 1; } 

That is all that remains. I just turned on int to verify and verify that assigning a value to it worked fine, and as long as the line is commented out. Any use of strings in the structure will fail.

I DO NOT NEED them there. I do not currently use these lines, I put them in the structure because I intend to use them later, but I can accomplish the same goal without them. Now I just want to understand why.

+4
source share
5 answers

This code is completely legal. The error is in the rest of your code.

+2
source

Code works fine: http://ideone.com/1NoMG

There must be something wrong in the code, or your compiler.

In addition, item1.item_name initialized when item1 . item1.item_name = "Name of Item"; is an appointment.

+2
source

Your code looks fine, but you may have memory corruption elsewhere in your code.

+2
source

The following compiler also works as expected with g ++ version 4.6.1 without any failure. You must have something else wrong.

 [21:18:32] user@host :[~]$ cat t.cpp #include <iostream> #include <string> using namespace std; struct item { string name; int number; }; int main() { item i; i.name = "blah"; i.number = 12; cout << "name=" << i.name << " number=" << i.number; } [21:18:34] user@host :[~]$ ./a.out name=blah number=12 [21:18:36] user@host :[~]$ 
+2
source

Do you have at least some global variable like Shadow? Perhaps the shadow global variable is not initialized when building another global one.

+1
source

Source: https://habr.com/ru/post/1401775/


All Articles