Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your not checking your pointers before accessing their values for dereference. This will automatically lead to undefined behavior if the pointer is invalid (NULL or indeterminate). With each implementation below, note we don't access data via dereference unless the pointer is first-known as valid:</p> <p><strong>Implementation: <code>insert()</code></strong></p> <pre><code>void insert(int id, int priority) { struct process **pp = &amp;head; struct process *element = malloc(sizeof(*element); element-&gt;id = id; element-&gt;priority = priority; while (*pp &amp;&amp; (*pp)-&gt;priority &gt;= priority) pp = &amp;(*pp)-&gt;next; element-&gt;next = *pp; *pp = element; } </code></pre> <p><strong>Implementation: <code>pop()</code></strong></p> <p>Your <code>pop()</code> function appears to be designed to return the popped value. While this isn't entirely uncommon it has the undesirable side-effect of having no mechanism for communicating to the <em>caller</em> that the queue is empty without a sentinel-value of some sort (such as (-1) in your case. This is the primary reason most queues have a <code>top()</code>, <code>pop()</code>, and <code>isempty()</code> functional interface. Regardless, assuming (-1) is acceptable as an error condition:</p> <pre><code>int pop() { struct process *tmp = head; int res = -1; if (head) { head = head-&gt;next; res = tmp-&gt;id; free(tmp); } return res; } </code></pre> <p><strong>Implementation: <code>popId()</code></strong></p> <p>Once again, looking for a specific node can be accomplished with a pointer-to-pointer in a fairly succinct algorithm, with automatic updating done for you due to using the actual physical pointers rather than just their values:</p> <pre><code>void popId(int id) { struct process ** pp = &amp;head, *tmp = NULL; while (*pp &amp;&amp; (*pp)-&gt;id != id) pp = &amp;(*pp)-&gt;next; if (*pp) { tmp = *pp; *pp = tmp-&gt;next; free(tmp); } } </code></pre> <p>I <em>strongly</em> advise stepping through each of these with a debugger to see how they work, particularly the <code>insert()</code> method, which has quite a lot going on under the covers for what is seemingly a small amount of code.</p> <p>Best of luck</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