diff --git a/src/protocols/secure_channel/CASESession.cpp b/src/protocols/secure_channel/CASESession.cpp index 007a58659f45cd..a012d12fcc56b4 100644 --- a/src/protocols/secure_channel/CASESession.cpp +++ b/src/protocols/secure_channel/CASESession.cpp @@ -428,12 +428,20 @@ void CASESession::Clear() mTCPConnCbCtxt.connClosedCb = nullptr; mTCPConnCbCtxt.connReceivedCb = nullptr; - if (mPeerConnState && mPeerConnState->mConnectionState != Transport::TCPState::kConnected) + if (mPeerConnState) { - // Abort the connection if the CASESession is being destroyed and the - // connection is in the middle of being set up. - mSessionManager->TCPDisconnect(mPeerConnState, /* shouldAbort = */ true); - mPeerConnState = nullptr; + // Set the app state callback object in the Connection state to null + // to prevent any dangling pointer to memory(mTCPConnCbCtxt) owned + // by the CASESession object, that is now getting cleared. + mPeerConnState->mAppState = nullptr; + + if (mPeerConnState->mConnectionState != Transport::TCPState::kConnected) + { + // Abort the connection if the CASESession is being destroyed and the + // connection is in the middle of being set up. + mSessionManager->TCPDisconnect(mPeerConnState, /* shouldAbort = */ true); + mPeerConnState = nullptr; + } } #endif // INET_CONFIG_ENABLE_TCP_ENDPOINT }