Weird, weird glitch in compiler

Ok so I spent about an hour with trying to figure out what the hell was going wrong. BTW I am not asking for help, just explaining how crazy this it.

Here's an example;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

const int NoP: 3;

struct testing{ string name; }

testing test[2] ={ 
                   { "Test1" },
                   { "Test2" }
                 };
int main()
{
string theChoice = "Test1";

 for(int x = 0; x < NoP; x++)
     {
        if( theChoice == test[x].name )
        {
          cout << "cool" << endl;
        }
     }
cin.get();
return 0;
}


This resulted in my program crashing, but if I changed the name "Test1" in the structure to ANYTHING else, it would work. It would alse work if theChoice was any other string as well.

To fix it, I ended up changing int NoP to something else and the program didn't crash! Then I went back and changed NoP to what it was before, and the crash didn't happen.

Crazy.
Nothing weird about it, that's just undefined behavior.
You're performing an invalid array access, so you can't exactly expect it to work...

Also, good rule of thumb: it's never a bug in the compiler, it's always you (except when it's not).
Nah, what I wrote up there isn't what I had in the program, just a generalization to explain what happened. But I was wrong, the problem didn't get fixed.

I fixed it though, but the thing that boggles my mind is why the program didn't crash if I ran a different string through the program..

Because the string was placed in the exact same location.
Last edited on
That's common with undefined behavior, especially if it involves invalid pointer accesses - sometimes it crashes, sometimes it doesn't, sometime it breaks other parts of the program by overwriting memory it shouldn't...
To see where the error(s) are, we need to see the actual code, though.
Yeah that is strange, it really messed me up because it only crashed for the one.
I found out where the error was so it is fine now.
Topic archived. No new replies allowed.