如何解决此C++访问冲突问题
how do I solve this C++ access violation problem?
我在以下代码中收到错误。 Visual Studio 在写入 _buf
时抛出访问冲突错误。 我该如何解决这个问题?
Sendn
函数是套接字发送函数。 这不是问题,你可以忽略它。
看起来_buf
点在0x00000000
我看到的错误消息是
0xC0000005: 0x00000000 : access violation
void ?????::?????(int number, string title)
{
int titlesize = sizeof(title);
int bufsize = 4 + 4 + 4 + titlesize;
char *_buf = new char[bufsize];
_buf = { 0 };
// char _buf[bufsize] = { 0 }; (수정 내용)
int commands = 3;
int index = 0;
memcpy(_buf, &commands, sizeof(int));
index += sizeof(int);
memcpy(_buf + index, &number, sizeof(int));
index += sizeof(int);
memcpy(_buf + index, &titlesize, sizeof(int));
index += sizeof(int);
for (int i = 0; i < titlesize; i++)
{
memcpy(_buf + index, &title[i], sizeof(char));
index += sizeof(char);
}
Sendn(_buf, bufsize);
delete[] _buf;
return;
}
char *_buf = new char[bufsize];
_buf = { 0 };
这不会对 _buf
指向的动态分配数组进行零填充。 它将指针_buf
设置为空指针。 由于 _buf
是一个空指针,因此以后尝试取消引用它会导致未定义的行为。
在这种情况下,无需对_buf
指向的数组进行零填充,因此您只需删除_buf = { 0 };
行即可。
修复该问题后,您也没有分配正确的内存量。 sizeof(title)
不会给你title
持有的字符数。 它只是为您提供std::string
对象的静态大小,通常只有一个指针和两个整数。 请改用title.size()
。
您正在尝试将title
的内容与其他 3 个整数一起复制到_buf
对吗?问题是sizeof(title)
不是存储在title
中的字符串的长度。为了得到title
的长度,你需要在类型std::string
上调用成员函数length
,如下所示:
auto titlesize = title.length();
sizeof
运算符只为您提供堆栈上std::string
对象的大小(相比之下,实际字符串存储在堆上(,sizeof
表达式始终是常量表达式。在我的计算机上,无论实际字符串是什么,sizeof(std::string)
都是 24。
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 读取访问冲突.这0xCDCDCDCD
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 插入数组时违反写访问冲突
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 尝试通过共享指针使用变量时读取访问冲突
- 堆栈上的 C++ 访问冲突写入异常
- 引发异常:写访问冲突. temp 为 nullptr
- 将静态字符数组中的字符分配给动态分配的字符数组 - 访问冲突
- 在C++中删除双向链表的头节点后出现访问冲突异常
- C++ 读取访问冲突,0xCDCDCDCD