-4

When I execute my program it doesn't terminate. I haven't changed anything and it has been working before. There is clearly something wrong but I don't understand what and why.

In the screenshot you can see the line

for ( size_t n = 0; n <= (size_t)maxState; n++ ) nodes.push_back(nullptr);

You can also see that maxState is -1, so (size_t)maxState should be 0. On the right side of the image you can see the values for n and the size of the nodes vector.

n goes to infitiny

I've taken the screenshot after pausing execution. When I resume it doesn't terminate. I've read some things about heap corruption, but without working solutions. Also I'm not sure if heap corruption is the real cause for this strange effect.

I already tried to clean and rebuild.

Sadık
  • 4,249
  • 7
  • 53
  • 89
  • 7
    *You can also see that `maxState` is -1, so `(size_t)maxState` should be 0.* Not at all, you might want to read [this question](https://stackoverflow.com/questions/2711522/what-happens-if-i-assign-a-negative-value-to-an-unsigned-variable). – Rakete1111 Oct 05 '17 at 15:28
  • 4
    where did you get the idea `(size_t)(-1) == 0`? – phuclv Oct 05 '17 at 15:32
  • I checked it before by doing `auto n = (size_t)maxState`. Also, I already mentioned that I haven't changed anything in the code. It has been working before. So it's totally wrong to mark this as duplicate. Maybe duplicate, but not to *that* question. – Sadık Oct 05 '17 at 15:34
  • Reopened; the duplicated addresses the **cause** of the problem, but doesn't address the appropriate **solution** here. – Pete Becker Oct 05 '17 at 15:37
  • 1
    @Sadik "_I checked it before by doing `auto n = (size_t)maxState`_", and yet, when I did the same in [this code snippet](https://ideone.com/cJIBWU), the cast doesn't make it equal to 0. So, it's still unclear where you got that assumption from. – Algirdas Preidžius Oct 05 '17 at 15:49
  • @AlgirdasPreidžius thank you. So I don't understand why it always had been 0 in thousands of tries before. The code is from a github repository btw. Nobody raised complains there about this line. – Sadık Oct 05 '17 at 15:51

1 Answers1

1

Don't mess with size_t here. You haven't mentioned the actual type of maxState, but if its value is -1, then it's a signed type. So use a signed index variable:

for (int i = 0; i < maxState; ++i)

This will execute zero times when the value of maxState is negative.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165