进入函数之前的访问冲突异常



我有这个函数,它只是简单地加密一个字符串(这个函数工作正常,并经过测试(。

DWORD SomeObj::Encrypt(string * To_Enc) {
    DWORD text_len = (To_Enc->length());
    if (!CryptEncrypt(this->hKey,
        NULL,  // hHash = no hash
        1,  // Final
        0,     // dwFlags
       (PBYTE)(*To_Enc).c_str(), //*pbData
       &text_len,  //*pdwDataLen
       128)) {      //dwBufLen
       return SERVER_ERROR;
    }
    return SERVER_SUCCESS;
}

我有这段代码:

string s= "stringTest";
Encrypt(&s);

它只是调用传递字符串指针的函数。

该程序在调用函数时会导致访问违规异常 Encrypt(&s) ,我想这是关于传递&s参数的事情,但我无法弄清楚这一点。从你的经验中知道吗?

这个答案将通过示例代码重申注释中已经提出的要点。

您当前的代码:

DWORD SomeObj::Encrypt(string * To_Enc) {
    DWORD text_len = (To_Enc->length());
    if (!CryptEncrypt(this->hKey,
        NULL,  // hHash = no hash
        1,  // Final
        0,     // dwFlags
       (PBYTE)(*To_Enc).c_str(), //*pbData
       &text_len,  //*pdwDataLen
       128)) {      //dwBufLen
       return SERVER_ERROR;
    }
    return SERVER_SUCCESS;
}

在线上:

(PBYTE)(*To_Enc).c_str(), //*pbData

请注意,您将从从 c_str (( 方法调用返回的指针值中放弃const -ness。

这应该立即成为一个危险信号;有时抛弃const-ness是一个有效的用例,但它更像是例外而不是规则。

未经测试,但使用临时的可变缓冲区应该可以解决您的问题,例如:

#include <cstddef>
#include <vector>
...
DWORD SomeObj::Encrypt(string * To_Enc) {
    std::vector<std::string::value_type> vecBuffer(To_Enc->length() * 3, 0);  // use the maximum value that could be output, possibly some multiple of the length of 'To_Enc'
    std::size_t nIndex = 0; 
    for (auto it = To_Enc->cbegin(); it != To_End->cend(); ++it)
    {
        vecBuffer[nIndex++] = *it;
    }
    DWORD text_len = (To_Enc->length());
    if (!CryptEncrypt(this->hKey,
        NULL,  // hHash = no hash
        1,  // Final
        0,     // dwFlags
       reinterpret_cast<PBYTE>(&vecBuffer[0]), //*pbData
       &text_len,  //*pdwDataLen
       vecBuffer.size())) {      //dwBufLen
       return SERVER_ERROR;
    }
    To_Enc->assign(&vecBuffer[0], text_len);  // assumes 'text_len' is returned with the new length of the buffer
    return SERVER_SUCCESS;
}

最新更新