进入函数之前的访问冲突异常
Access Violation exception before entering into a function
我有这个函数,它只是简单地加密一个字符串(这个函数工作正常,并经过测试(。
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;
}
相关文章:
- 写入访问冲突异常
- 在C++中删除双向链表的头节点后出现访问冲突异常
- Visual Studio图形调试器引发读取访问冲突异常
- 尝试将 std::cerr 重定向到文件时出现访问冲突异常
- 媒体基础:读取示例 - 访问冲突异常
- 链表的访问冲突异常
- 进入函数之前的访问冲突异常
- 删除函数 c++ 的读取访问冲突异常
- 无法使用 C++ catch(..) 捕获访问冲突异常
- 在Visual Studio Community中使用glfw3 glew和opengl获取访问冲突异常
- 访问动态 2D 字符数组时引发访问冲突异常
- 从静态库使用 Boost Asio 时访问冲突异常
- 为什么访问冲突异常不能被 捕获.NET4.0.
- glGenBuffers 访问冲突异常
- unsigned char*导致访问冲突异常
- 注入DLL的函数中出现访问冲突异常(5)
- 删除二叉搜索树中的节点中的 Visual Studio 中的访问冲突异常
- 提升 Asio tcp::接受者访问冲突异常
- 在 .Net 应用程序中调用 C++ DLL 时出现系统访问冲突异常
- 为什么此代码会引发访问冲突异常