Advertisement

What Happens To The buf Parameter Of send()?

Started by March 06, 2005 11:09 AM
2 comments, last by jtmerchant 19 years, 11 months ago
When I, personally, call send, I do something like this:
str=new char[100];
str="!QUERY!LUVERSION~$";
debugResult=send(clientSock,str,StringLength(str,'$'),0);
Now that being so, does str get copied and the copy is sent over the network or how does that work? What I suppose I really need to know is can I type this:
delete str;
right after, without future issues? Will the client still recieve the message unhindered? I'm guessing it would be OK, since it works currently, but just wanted to make sure its not gonna explode when I use multiple computers to test or anything. [Edited by - jtmerchant on March 6, 2005 12:45:05 PM]
Quote:
str=new char[100];
str="!QUERY!LUVERSION~$";


You've overwritten the contents of the pointer with the address of a static string. The address returned by new char[100] is lost (memory leak), and delete[]-ing a static string has undefined behaviour.

Also note that since you're using the array-new you must use array-delete.

Here's the corrected code:
str=new char[100];strcpy(str, "!QUERY!LUVERSION~$");debugResult=send(clientSock,str,StringLength(str,'$'),0);delete[] str;

or, dispensing with the dynamic buffer altogether:
const char* str = "!QUERY!LUVERSION~$";debugResult=send(clientSock,str,StringLength(str,'$'),0);


Though of course, it is much simpler to use a C++ string:

std::string str;str = "!QUERY!LUVERSION~$";debugResult=send(clientSock,str.c_str(),str.length()-1,0); // -1 for the $// no cleanup needed
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Advertisement
Yes, the buffer is copied.

However, calling delete str in this context is undefined. You see; str points to a string literal, not dynamic memory. All you did when you created the string was create a memory leak. You dynamically allocated a string, then immediatly assigned a string literal to the variable, thus loosing the location of the memory you just allocated so you can't ever delete it.

Just do const char* str = "..."; and don't worry about deleting it.

[edit] I swear you must be out to get me Fruny. :P [/edit]
I've been doing that for weeks. Don't I feel sheepish.

This topic is closed to new replies.

Advertisement