Pointer not updating in main

2019-09-03 13:03发布

I have a main program in another file calling a function cbuf_update() that in turn calls cbuf_sizeChange() Here is what is confusing me: Within cbuf_update, calling cbuf_sizeChange properly updates cb_ptr, but in main.c, it is garbage from when I freed cb1 in sizeChange(). I cannot make it static because there are a variable number of cbufs in main. What do I do? I cannot change the signature of cbuf_update().

Struct def:

typedef struct cbuf {
    unsigned int max;
    unsigned int start;
    unsigned int end;
    unsigned int size;
    quote *quotes;
} cbuf;

Call from main.c:

cbuf *eur_jpy;
eur_usd = cbuf_init() ;
cbuf_update(eur_jpy, time, rate) ;

Relevant methods in other file:

cbuf * cbuf_init()
{
    //initialize the cbuf with malloc

    return cb1;
}

void cbuf_update(cbuf *cb_ptr, double rate)
{
    cb_ptr = cbuf_sizeChange(cb_ptr, 2);
}

cbuf *cbuf_sizeChange(cbuf *cb1, double factor)
{
        cbuf *cb2;
    quote *quotes;
    quotes = (quote *)malloc(cb1->max * factor * sizeof(quote));
    cb2 = (cbuf *)malloc(sizeof(*quotes) + 4 * sizeof(unsigned int));

        //Update quotes here(exluding it)

        cb2->size = cb1->size;
    cb2->end = cb1->size - 1;
    cb2->max = factor * cb1->max;
    cb2->start = 0;
    free(cb1->quotes);
    free(cb1);

    cb2->quotes = quotes;

    return cb2;
}

1条回答
Luminary・发光体
2楼-- · 2019-09-03 13:44

This bit doesn't look right:

void cbuf_update(cbuf *cb_ptr, double rate)
{
    cb_ptr = cbuf_sizeChange(cb_ptr, 2);
}

It modifies cb_ptr, which is a local copy of whatever you passed into cbuf_update() as the first parameter.

You might want to think along these lines:

void cbuf_update(cbuf **cb_ptr, double rate)
{
    *cb_ptr = cbuf_sizeChange(*cb_ptr, 2);
}

and instead of calling cbuf_update(something, rate) call cbuf_update(&something, rate).

查看更多
登录 后发表回答