【问题标题】:Access Violation exception before entering into a function进入函数前的访问冲突异常
【发布时间】:2018-08-24 05:41:22
【问题描述】:

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

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 的问题,但我无法弄清楚。根据您的经验有什么想法吗?

【问题讨论】:

  • 你不能通过std::string::c_str()返回的指针改变std::string的内容
  • 您也没有提供 128 字节的缓冲区。
  • 那绝对不是真的,我已经成功做到了一百次...@RichardCritten
  • "...写入通过 c_str() 访问的字符数组是未定义的行为...。" 来源:en.cppreference.com/w/cpp/string/basic_string/c_str UB 包括出现意外工作。
  • @LAvR 您不能通过写入底层存储来扩展std::string。如果它在不同的项目中起作用,那么你只是运气不好。

标签: c++ string parameter-passing wincrypt


【解决方案1】:

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

您当前的代码:

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;
}

【讨论】:

  • @LAvR 很高兴,很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多