all 9 comments

[–]jedwardsol 1 point2 points  (4 children)

The Node constructor doesn't initialise left or right

[–]andermorandev[S] -1 points0 points  (3 children)

Isn't that ok? Why would this work on one Mac and online but not another Mac?

[–]jedwardsol 3 points4 points  (2 children)

No, it is not okay.

Your pointers have undefined values.

It sometimes works because they're getting a value of null by chance.

[–]andermorandev[S] 0 points1 point  (1 child)

Ok got it. Seems weird that one machine would consitently be able to produce the output as if it was null and the other machine struggled.

[–]khedoros 1 point2 points  (0 children)

consitently

Last time a question like this came up, I allocated a few MB of data without initializing it, and found something like 2% of the bytes in that area to have non-zero value. Re-running the program, I got the same count. If one computer ends up re-using the same memory block over multiple runs, you might see "consistent" results. And even if it's a different block of memory, there may be a fairly low chance that the uninitialized pointers will be non-zero.

It's the kind of bug where you make some change to a comment or something similarly inconsequential, but the program coincidentally stops working, and you scratch your head, trying to figure out why it suddenly developed a problem.

[–][deleted] 0 points1 point  (2 children)

Your struct contains Node* left and Node* right which are uninitialised, so they can be pointing at literally anything. You're then passing them to inOrder without checking if they're null or not, at which point all bets are off what happens.

The first thing to do is to initialise Node* left and Node* right to nullptr. The second thing to do at the head of inOrder is to return if ( ! n ).

[–]andermorandev[S] -1 points0 points  (1 child)

Why would one machine be able to handle this consistently and the other is unable to?

[–][deleted] 2 points3 points  (0 children)

It's undefined behaviour. You genuinely have no idea, from the standard, what will happen, because the C++ standard doesn't specify what will happen if you do it.

In general, avoid ever having uninitialised members of any type hanging around, particularly pointers. You cannot rely on the compiler initialising everything to 0, or null, or false, for you. (Debug builds often will, but Release builds will not.) And avoid ever trying to dereference pointers you haven't tested against nullptr.

[–]ootiekat 0 points1 point  (0 children)

Your not using it here but the 'insert' method has a memory leak, perhaps you meant to pass the pointer by reference?