new/delete when we have a callback

X

xenonysf

they give me function pointer for call back;
here is the func;

funcA(void* buffer,int size);

when i receive data i am goinf to call this func, buffer with data and
its size..
i have data listener thread; i receive data like this;

void* d = malloc(100);
recv(d,100);

then i call callback;

cb(d,100);

so; when we put this code in to a loop to receive&call continuesly,
a memory leak occurs... unless this buffer is not freed in callback
func.
Now i am free ing after calling callback... (after line cb(d,100); ),
i hesitate; is this the correct strategy....?
 
M

mlimber

xenonysf said:
they give me function pointer for call back;
here is the func;

funcA(void* buffer,int size);

when i receive data i am goinf to call this func, buffer with data and
its size..
i have data listener thread; i receive data like this;

void* d = malloc(100);
recv(d,100);

then i call callback;

cb(d,100);

so; when we put this code in to a loop to receive&call continuesly,
a memory leak occurs... unless this buffer is not freed in callback
func.
Now i am free ing after calling callback... (after line cb(d,100); ),
i hesitate; is this the correct strategy....?

Generally, if you allocate something, you should free it (directly, or
indirectly through RAII) or you should make it clear to your clients
that they are responsible for freeing it by using a smart pointer such
as std::auto_ptr. In the case of an array, you should use a container
that will clean itself up such as std::vector. See
http://www.parashift.com/c++-faq-lite/containers.html#faq-34.1.

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top