【问题标题】:What's wrong with my ClientConnection class? C++我的 ClientConnection 类有什么问题? C++
【发布时间】:2012-06-18 03:52:26
【问题描述】:

假设我的头文件和一些包含的库没有问题。我正在使用 Winsock2。

//main.cpp and this code is okie, I omit some codes for readable reason
SOCKET ClientSocket;
ClientSocket = INVALID_SOCKET;
ClientSocket = accept(ListenSocket, NULL, NULL);
cout <<"a client is connected" << endl;
ClientConnection connection(ClientSocket);
connection.run();

//ClientConnection.h I tested any function and it's okie
class ClientConnection{
    private:
        SOCKET connectedSocket;
        bool connected;
    public:
        ClientConnection(const ClientConnection &con);
        ClientConnection(SOCKET s);
        int processMessage(string message);
        void sendMessage(string message);
        string recvMessage();
        int run();
        void printSomething(); //function just print something such as :"Here"
};

run() 函数中,我调用recvMessage() 从客户端获取消息,然后调用processMessage(message)。这是我的processMessage(message)sendMessage

void ClientConnection::sendMessage(string mess){
    const char* sendBuff = mess.c_str();    
    int error = send(this->connectedSocket,sendBuff, (int)strlen(sendBuff), 0);
    delete sendBuff;
    return ;
}
int ClientConnection::processMessage(string message){
    cout << "This is message from client:\n" << message << endl;
    ImageProcessingPlugin *plugin = new ImageProcessingPlugin();
    plugin-> processMessage( *this, message);
    delete plugin;
    return 0;
}

这是 ImageProcessingPlugin:

// ImageProcessingPlugin.h
class ImageProcessingPlugin : public Plugin{
public:
    ImageProcessingPlugin();
    void processMessage(const ClientConnection &connection, string message);
};
// ImageProcessingPlugin.cpp
void ImageProcessingPlugin::processMessage(const ClientConnection& _connection,  string message){
    ClientConnection connection(_connection);
    connection.printSomething() // It's okie
    connection.sendMessage("Server received"); // Problem goes here!!
    return;
}

经过调试,当我在plugin-&gt;processMessage中调用printSomething()时,还是可以的,但是当我转到sendMessage时,客户端仍然收到来自服务器的消息“服务器已接收”,但出现错误:“ _Block_Type_IS_VALID(pHead->nBlockUse)”!谁能解决我的问题?

【问题讨论】:

    标签: c++ visual-c++ winsock2


    【解决方案1】:

    您在此处删除delete sendBuff;,但您从未自己分配内存。尝试删除该行。

    【讨论】:

    • 真的很有帮助!但是,为什么我必须在这里删除delete sendbuff
    • @Kingfisher:std::string 为您管理内存,因此您永远不应该在由std::string 管理的内存上调用delete
    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 2013-09-30
    • 2017-05-02
    • 1970-01-01
    • 2017-11-27
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多