Reallocating array causes "Aborted" error
<p>I wrote the following struct for a vector:</p>

<pre><code>typedef struct Vector_ Vector;

struct Vector_
{
    int dim;
    double* vector;
};
</code></pre>

<p>And I wrote a function to initialise a new instance of that struct: </p>

<pre><code>Vector* newVector(int length){
    int i = 0;
    Vector* vec = malloc(sizeof(Vector));
    assert(vec != NULL);
    assert(length &gt; 0);


    vec-&gt;dim = length;
    vec-&gt;vector = malloc((length+1)*sizeof(double));
    assert(vec-&gt;vector != NULL);
    for(i=0;i&lt;=length+1;i++) vec-&gt;vector[i] = 0;
    return vec;
}
</code></pre>

<p>This all works, but then I wrote a function to reallocate memory and change the length of the vector like this: </p>

<pre><code>Vector* setVectorLength(Vector* vec, int length)
{
    assert(vec-&gt;dim &gt; 0);
    int i = 0;
    if(length &gt; vec-&gt;dim)
    {
        vec-&gt;vector = realloc(vec-&gt;vector,(length+1)*sizeof(double));
        assert(vec-&gt;vector != NULL);
        for(i = vec-&gt;dim+1;i&lt;=length;i++)
        {
            vec-&gt;vector[i] = 0;
        }
    }
    else
    {
        vec-&gt;vector = realloc(vec-&gt;vector,length+1 * sizeof(double));
    }
    vec-&gt;dim = length;
    return vec;
}
</code></pre>

<p>And I call it like this:</p>

<pre><code>int main()
{
    Vector* newvec = newVector(5);
    setVectorLength(newvec,8);
}
</code></pre>

<p>For some reason, the line in the setVectorLength function where I reallocate the memory of the vector array causes the program to abort. If I comment out that section, everything works. Interestingly, I am able to write entries to the array even without reallocating it to a sufficiently high length, so for example, if I only initialise the vector struct and give it the length 5, then I can write values into the 7th or 8th spot of the vec->vector array, even though I never allocated that much memory to it. Any hints?</p>