delete operator unable to free data

while(1)
{
newServ.ReceiveRequest();
char *recvBuffer = new char[4096];

newServ.ReceiveData(recvBuffer, 4096, 0);
delete[] recvBuffer;
recvBuffer = NULL;
}

This server code is expected to receive new data in 'recvBuffer'. But donno why it doesnt clear the data received in previous iteration. It sort of mixes current data and previous data...

Can anybody pls help me with this..??

Thanks in advance,
Regards,
Aditi
why are you doing both the thing
1
2
delete[] recvBuffer;
recvBuffer = NULL;

i am not surly but this might possible that it causes problem to you..
so please remove recvBuffer = NULL; from your code.
Nope ...even after removing recvBuffer = NULL its not working... I did that coz delete[] frees up memory but pointer keeps on pointing to the same location hence becomes dangling pointer...
You were right to do so.

Nothing here is invalid, we'd need to see the code of RecieveData. Chances are the issue is in there.
int OdlServer :: ReceiveData(void *buffer, int bufferlen, unsigned int flags)
{
int bytes_recvd;
bytes_recvd = recv(new_sock_des, buffer, bufferlen, 0);
if(bytes_recvd != -1)
cout<<"Data received Successfully"<<" "<<bytes_recvd;
return bytes_recvd;
}

this is code for ReceiveData() which calls recv() function which is built-in.
why not use a static char array buffer to avoid new/free frequently?

while(1)
{
newServ.ReceiveRequest();
static char recvBuffer[4096];
recvBuffer[0] = '\0'; // you can do a memset here, but time consuming

newServ.ReceiveData(recvBuffer, 4096, 0);
// process buffer data here
}

You're not using the return value from OdlServer::ReceiveData(), which tells you exactly how many bytes were written to the destination array. Without that information, you can't know where the current transmission ends. And since new is likely returning the same pointer over and over again, the bytes from the last transmission are still there, confusing you into thinking some incorrect code has overwritten the buffer.

PS: What, is it now hip to not use frakking [code] tags?
Last edited on
why not use a static char array buffer to avoid new/free frequently?
No, don't do that! It makes your function non-reentrant, non-threadsafe, and hogs a fixed block of memory that could be otherwise used by something else.

why are you doing both the thing
delete[] recvBuffer;
recvBuffer = NULL;
That's good practice, don't change it.
Topic archived. No new replies allowed.