Search code examples
crealloc

Unexpected realloc() behaviour


As part of a larger program, I have a method which computes the coefficients of the derivative of a polynomial. But that's not the problem:). In the following code, if I skip the realloc() call, I get the results I expect in (*coef). With the realloc one of the elements is set to 0. Is this my fault, or is the realloc() behaviour actually unexpected?

void derive (double **coef, int size)
{
    int i;
    if (size<2)
        free_vector (*coef);
    else
    {
        for (i=0; i<size-1; ++i)
        {
            (*coef)[i] = (*coef)[i+1]*(i+1);
        }
        (*coef) = realloc ((*coef), size-1);
    }   
}

I'll also attach the complete source code for a test program if running it would help...

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double *new_vector (int size)
{
    double *vec = calloc (size, sizeof (double));
    return vec;
}

void free_vector (double *vec)
{
    if (vec)
    {
        free (vec);
        vec = NULL;
    }
}

void write_vector (FILE *f, double *vec, int size)
{
    int i;
    for (i=0; i<size; ++i)
        fprintf (f, "%1.15lf\n", vec[i]);
    fprintf (f, "\n");
}

void derive (double **coef, int size)
{
    int i;
    if (size<2)
        free_vector (*coef);
    else
    {
        for (i=0; i<size-1; ++i)
        {
            (*coef)[i] = (*coef)[i+1]*(i+1);
        }
        (*coef) = realloc ((*coef), size-1);
    }   
}

int main (void)
{
    double *v = new_vector (5);
    int i;
    for (i=0; i<5; ++i)
        v[i] = 3;
    write_vector (stdout, v, 5);
    derive (&v, 5);
    write_vector (stdout, v, 4);
    free_vector (v);
    return 0;
}

Solution

  • Realloc takes a number of bytes.

    realloc ((*coef), (size-1) * sizeof(double));
                               ^^^^^^^^^^^^^^^^