Whenever a new client connects, a new std::string instance is created in heap inside the .message callback and set with a value sent by the client (the message object).
I can see the memory (RSS tab) keeps increasing with new each client connection (for example, 9000 something bytes, then 9004 something bytes, then 9008 something bytes, and so on for each two or three new clients), but it's not decreasing even when I am deleting the object in the .close callback when each of those clients exits properly. clientSocket.close() is called from the client side (Qt C++ QWebSocket) and the .close callback is fired on the server side.
For testing, I am sending 1024 bytes from each client.
I am using the following command line to watch the memory usage in real time in Linux Debian.
watch -n0.2 'pmap -x process-id | tail -n1'
I must be doing something very wrong. I am a noob in using this library.
This is the user data structure:
struct PerSocketData { std::string* someString {nullptr}; }; .message = [&](uWS::WebSocket<false, true, PerSocketData> *ws, std::string_view message, uWS::OpCode opCode) { PerSocketData* ud = ws->getUserData(); ud->someString = new std::string(message); } In the .close callback, I am deleting the object as following:
.close = [](uWS::WebSocket<false, true, PerSocketData> *ws, int /*code*/, std::string_view message) { PerSocketData* ud = ws->getUserData(); ud->someString->clear(); //looks dumb but since the delete wasn't working hence I tried this as well ud->someString->shrink_to_fit(); //looks dumb but since the delete wasn't working hence I tried this as well delete ud->someString; ud->someString = nullptr; }
std::stringat all? You don't need to do that in this code, this will suffice:struct PerSocketData { std::string someString; };Also, there is no need to callclear()orshrink_to_fit()before destroying astd:string. But, where is thePerSocketDataallocated and freed? In any case, if you are just looking at memory usage at the OS level, then it's likely that your app is just caching freed memory for later reuse, which is fairly common practice for any non-trivial app that uses a memory manager layer and doesn't allocate OS memory directly.deletean object all you do is tell theC++runtime that the memory associated with that object is no longer required. It needn't return the memory to the global 'pool' immediately. As such, something like task manager is really not a useful tool for diagnosing such issues.std::stringis a specialized smart pointer for strings. Having a pointer-to-a-string is really odd, since string itself is already a smart pointer.