意外的realloc()行为

时间:2011-04-07 18:32:56

标签: c realloc

作为更大程序的一部分,我有一种计算多项式导数系数的方法。但那不是问题:)。在下面的代码中,如果我跳过realloc()调用,我会得到我期望的结果(* coef)。使用realloc将其中一个元素设置为0.这是我的错,还是realloc()行为实际上是意外的?

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);
    }   
}

如果运行测试程序,我还会附上测试程序的完整源代码......

#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;
}

1 个答案:

答案 0 :(得分:8)

Realloc需要多个字节。

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