1
votes

I am writing a server program which has a function to pack a struct to a protocol-confining struct. The function looks like this:

lpacket pack_interp_ilpacket(ilpacket* pck)
{
    lpacket* a = malloc(pck->size);
    pack_lpack_data(pck->size, pck->msgtype, pck->following, a);

    return *a;
}

Now the problem is, when I call malloc on the lpacket and dereference it to make it return a value (and not a reference), I am no longer able to free that memory. If I call free at the place where the value is returned, I only free the stack-allocated struct. And a call to free AFTER the return statement wouldn't make much sense...

Any ideas?

1
should be returning the pointer a if you want to free it outside (since this is what you are allocing).. - amdixon
Yup, but I actually want the value and not the pointer. Does that mean there's no way to free the allocated memory? - Henrik Hillestad Løvold
if you return the pointer the value is *pointer. this would be the way to handle it if you want to return allocd memory - amdixon
I'm guessing lpacket has a flexible array member, is that right? And to answer you question in-comment, that is exactly what that means. you're leaking memory in three short lines (2 shy of the record). Do you own this function, and is it some callback and therefore an unmodifiable signature? - WhozCraig
It would be interesting to know how lpacket is declared. - alk

1 Answers

1
votes

You can pass by pointer a second argument to the function as pointer to lpacket as below and allocate memory of size pck->size to lpck before calling this function and free the memroy after this function returns successfully.

void pack_interp_ilpacket(ilpacket* pck,lpacket* lpck) { pack_lpack_data(pck->size, pck->msgtype, pck->following, lpck); }