Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Intermittent segfaults in c/c++ programs are usually caused by uninitialised memory, often in pointer variables.</p> <p>You've posted a lot of code, which makes it hard to debug just be reading it. I suggest going through the code and, wherever a variable is declared, giving it an initial value (e.g. zero or NULL). Remember that the compiler will not initialise them for you.</p> <p>You should probably start by initialising the values of <code>num</code> and <code>head</code> in <code>main()</code>. E.g.</p> <pre><code>int num = 0; nodePtr head = NULL; /*head of the list*/ </code></pre> <p><strong>EDIT 1</strong></p> <p>Another bug is in <code>addToList()</code>. If the first <code>if</code> block in that function is not executed then the value of the local variable <code>p</code> will be uninitailised when you later call <code>realloc(p-&gt;arr, ...)</code>. When you dereference <code>p</code> to get <code>p-&gt;arr, if</code>p` is uninitialised then you will <em>usually</em> get a segfault.</p> <p><strong>EDIT 2</strong></p> <p>Two useful techniques when programming in C/C++ :</p> <ol> <li>Always initialise variables at the point that you declare them. If you don't then their value is undefined. Note that this doesn't solve all problems. If you dereference an uninitialised pointer then you will <em>usually</em> get a segfault. If you initailise it to null and then dereference it then you will always get a segfault. Easier to debug, but it still crashes.</li> <li>Always declare variables as near as possible to the point in the code that you first use them. This has the effect of reducing the chances of using an uninitialised variable because the compiler will generate an 'undeclared variable' error. The practice of declaring all variables at the start of a function is a hangover from old-style <a href="http://en.wikipedia.org/wiki/C_%28programming_language%29#K.26R_C" rel="nofollow">'K&amp;R' C</a>, where you had to do that. Modern C doesn't require it.</li> </ol> <p>So, instead of:</p> <pre><code>int foo() // Warning: bad code { int a; int b; func1(); a=func2(&amp;b); return a; } </code></pre> <p>try something like:</p> <pre><code>int foo() { func1(); int b = 42; int a = func2(&amp;b); return a; } </code></pre>
 

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