Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason why the code segfaults when you uncomment the printf statement is because rootNode is a NULL pointer. Dereferencing this NULL pointer in the function call causes the segfault.</p> <p>The reason that rootNode is a NULL pointer is that it is never changed by the code. Calling <code>insertNode()</code> results in the local variable <code>n</code> being set to the value that is stored in <code>rootNode</code> (in this case NULL). The changes to <code>n</code> in the <code>insertNode()</code> function do not change <code>rootNode</code>. </p> <p>To fix the code you could change the <code>insertNode</code> and <code>deleteNode</code> functions to accept a pointer to the root node pointer. For example the <code>insertCode()</code> function would become:</p> <pre><code>void insertNode(int i, node **n) { if(*n == NULL) { (*n) = (node*)malloc(sizeof(node)); (*n)-&gt;leftChildNode = NULL; (*n)-&gt;rightChildNode = NULL; (*n)-&gt;data = i; } else { if((*n)-&gt;data == i) { printf("\nThis value already exists in the tree!"); } else { if(i &gt; (*n)-&gt;data) insertNode(i, &amp;(*n)-&gt;rightChildNode); else insertNode(i, &amp;(*n)-&gt;leftChildNode); } } } </code></pre> <p>You would also have to change the code to call <code>insertNode()</code> with a reference to rootNode <code>insertNode(num, &amp;rootNode);</code></p> <p>I also recommend that you check the return values of the various scanf calls. If <code>scanf("%d",x)</code> returns 0 then the value not be converted to an int and the contents of x are undefined. Ideally the code would handle this case gracefully. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload