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;
}
This bit doesn't look right:
It modifies
cb_ptr
, which is a local copy of whatever you passed intocbuf_update()
as the first parameter.You might want to think along these lines:
and instead of calling
cbuf_update(something, rate)
callcbuf_update(&something, rate)
.