Reputation: 3
I'm getting an error in the following code. Visual Studio throws an access violation error when writing to _buf
. How can I fix this?
The Sendn
function is a socket sending function. It's not the problem, you can ignore it.
It looks like _buf
points at 0x00000000
The error message I'm seeing is
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;
}
Upvotes: 0
Views: 563
Reputation: 521
You're trying to copy the content of title
together with 3 other integer numbers into _buf
right? The problem is that sizeof(title)
is not the length of the string stored in title
. In order to get the length of title
, you need to call the member function length
on type std::string
like this:
auto titlesize = title.length();
The sizeof
operator only gives you the size of your std::string
object on stack (in comparison, the actual string is stored on heap) and sizeof
expressions are always constant expressions. On my computer, sizeof(std::string)
is 24 regardless of what the actual string is.
Upvotes: 0
Reputation: 30494
char *_buf = new char[bufsize];
_buf = { 0 };
This does not zero-fill the dynamically-allocated array pointed to by _buf
. It sets the pointer _buf
to be a null pointer. Since _buf
is a null pointer, later attempts to dereference it lead to undefined behavior.
There's no need to zero-fill the array pointed to by _buf
in this case, so you can simply remove the _buf = { 0 };
line.
Once you've fixed that problem, you also aren't allocating the right amount of memory. sizeof(title)
will not give you the number of characters that title
holds. It just gives you the static size of a std::string
object, which is usually only a pointer and two integers. Use title.size()
instead.
Upvotes: 2