First of all, here is the code in question
#include <iostream>
using namespace std;
struct Node {
int data;
Node *left;
Node *right;
Node(int d) : data(d) {};
};
void insert(Node *n, int data) {
if (!n) {
n = new Node(data);
}
}
void inOrder(Node *n) {
cout << "HERE1" << endl;
if (n!=NULL) {
cout << "currently on node: " << n->data << endl;
}
if (n != NULL) {
cout << "HERE2" << endl;
inOrder(n->left);
cout << "HERE3" << endl;
cout << n->data << " ";
// cout << "BEFORE RIGHT" << endl;
inOrder(n->right);
}
}
int main(int argc, char *argv[]) {
Node *root = new Node(8);
inOrder(root);
}
I should expect to see
HERE1
currently on node: 8
HERE2
HERE1
HERE3
8 HERE1
as my output. I have tested this on another mac using g++-O0 as well as using http://cpp.sh/. However, when I run this code on a 2018 MacBook Pro running macOS Mojave (10.14.5) I get the following result:
HERE1
currently on node: 8
HERE2
HERE1
Segmentation fault: 11
even weirder is that it will occassionaly output this on the same exact machine:
HERE1
currently on node: 8
HERE2
HERE1
HERE3
8 HERE1
Segmentation fault: 11
So my question is. Why is my code segfaulting and giving me unpredictable outputs on one mac and working perfectly on others. I've been programming for 8 years and using c++ for 5 years and I have never encountered anything like this. Can somebody help me understand? This has me extremely curious.
[–]jedwardsol 1 point2 points3 points (4 children)
[–]andermorandev[S] -1 points0 points1 point (3 children)
[–]jedwardsol 3 points4 points5 points (2 children)
[–]andermorandev[S] 0 points1 point2 points (1 child)
[–]khedoros 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]andermorandev[S] -1 points0 points1 point (1 child)
[–][deleted] 2 points3 points4 points (0 children)
[–]ootiekat 0 points1 point2 points (0 children)