Why is this instance of realloc giving me SIGABRT?
<p>Here is the code in question, it's a function that reallocs a int array and adds a number to the end of it</p>

<pre><code>int *add_to_array(int *arr, unsigned int num, int newval)
{
    if(arr != NULL){

        int *newarr = realloc(arr, sizeof(int) * (num+1));
            if(!newarr){
                free(arr);

            }else{
                free(newarr);
            }
            arr[num] = newval;
            return arr;
   }
   else{

    return NULL;

   }

}
</code></pre>

<p>Problem is, when I call this function once, it works fine, but if I call it a second time, the debugger gives me a SIGABRT at the line</p>

<pre><code>int *newarr = realloc(arr, sizeof(int) * (num+1));
</code></pre>

<p>Here is how I'm calling the function</p>

<pre><code>array = add_to_array(array, 5, 10);
array = add_to_array(array, 6, 100);
</code></pre>

<p>EDIT: I managed to solve this with this new code</p>

<pre><code>int *add_to_array(int *arr, unsigned int num, int newval)
{
if(arr != NULL){

int *newarr =realloc(arr, sizeof(int) * (num+1));
if(!newarr){
    return NULL;
}else{
 newarr[num] = newval;
 return newarr;
}
}
else{

    return NULL;

}

}
</code></pre>

<p>One more question, in the event whereby realloc fails to realloc the given pointer arr, does arr becomes null in that instance or is it still valid?</p>