Variable value changes per se

I was quite confused during programming before, but this one takes the cake. Basically, I set the value in one for loop, and in the next iteration it changes to the value of the next.

for (int i = 0; i < 2; ++i) { for (int j = 0; j < numWords[i]; ++j) //numWords [0] = 9, numWords [1] = 7 { stb[i][j].word = const_cast<char*>(is (j + 1,1).c_str()); //is(int,length[opt]) converts int to string, c_str() returns const char *, but I need char * cout << is(j+1,1) << ' ' << stb[i][j].word << '\n'; } } for (int i = 0; i < 2; ++i) { for (int j = 0; j < numWords [i]; ++j) { cout << stb[i][j].word << ' '; } cout << '\n'; } 

Output:

  eleven
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9
 eleven
 2 2 
 3 3
 4 4
 5 5 
 6 6
 7 7 
 7 7 7 7 7 7 7 7 7
 7 7 7 7 7 7 7

My only assumption is that there is something with a constant, but it does not make sense why it will modify all previous elements of the array ...

+4
source share
1 answer

It is pretty simple. Your program has undefined behavior (if my assumptions about is() are correct).

is(int, length) returns the value of std::string by value. You get a pointer to some internal structure in string using c_str() . Then this line is destroyed at the end of the full expression. This destruction invalidates the pointers you received from c_str() .

This means that you are filling the array with pointers to invalid memory. Then you read these pointers to print the contents of the array. Reading from invalid memory results in undefined behavior.

A possible explanation for the observed behavior is as follows:

Each string that is returns the reuse of the same memory. In the first loop, you read from memory before it is overwritten by another call to is , and you get the correct value. In the second loop, you read from memory after it has been overwritten, and you will get the final value in the array.

+3
source

All Articles