【发布时间】:2019-12-04 07:53:15
【问题描述】:
我在以下代码中遇到错误。写入 _buf 时,Visual Studio 会引发访问冲突错误。我该如何解决这个问题?
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;
}
【问题讨论】:
-
你是什么原因
memcpy()-ingtitle,一次一个字符,有自己专用的for循环,而不是简单地memcpy()ing 整个事情,一口气? -
旁注,虽然我认为这不是问题,但作为一般规则,starting symbol names with an underscore is a bad idea 因为如果操作不当,可能会导致意外使用一些保留的标识符。
-
其他注意事项:您可能应该执行
int bufsize = sizeof(int) + sizeof(int) + sizeof(int) + titlesize;之类的操作,而不是int bufsize = 4 + 4 + 4 + titlesize;,因为intis not guaranteed to be 4 bytes。
标签: c++