How to add 0x00 at the end of a buffer
I have a piece of code as:
char* buffer = new char[12];
memcpy(newbuffer, bytes, 10); //bytes is const void *
Now I want the last 2 bytes which I have not used should be appended with 开发者_JAVA技巧0000
.
How can I achieve that?
Easy as this:
buffer[10]=buffer[11]=0;
If it was a longer range you could have used memset
or std::fill
.
Use memset.
memset(buffer + 10, 0, 2);
Initialize the whole buffer before calling memcpy
and its done for you:
char* buffer = new char[12];
memset(buffer, 0, 12);
memcpy(buffer, bytes, 10);
You can just assign them directly:
buffer[10] = 0;
buffer[11] = 0;
Or put it in a loop if you prefer.
Just set them to 0.
buffer[10] = buffer[11] = 0;
errr..
buffer[10] = 0;
buffer[11] = 0;
If you need to do that for more than only two elements:
memset( & buffer[10], 0, 2 );
More generic:
// sets the next n elements of your array of type T
// pointed by pointer to 0.
memset( pointer, 0, n*sizeof(T) );
For just two elements the simple solution already suggested by many will probably be clearer and faster.
Since you are using C++, you should eschew manual memory management and use the Standard Library facilities that are available to you, like std::vector
. It is near impossible to correctly manage memory manually in C++ and it is completely necessary in all but a select few cases (like in low-level library code).
Given:
const char* bytes;
std::size_t n_bytes = 10;
Any of the following will work:
std::vector<char> buffer(bytes, bytes + n_bytes);
buffer.push_back(0); // null-terminate the buffer
or:
std::vector<char> buffer(n_bytes + 1);
std::copy(bytes, bytes + n_bytes, buffer.begin());
or:
std::vector<char> buffer;
buffer.reserve(n_bytes + 1);
std::copy(bytes, bytes + n_bytes, std::back_inserter(buffer));
buffer.push_back(0);
Which performs best depends on how std::vector
is implemented by your compiler. In practice, unless you are creating and destroying buffers at a relatively high frequency, you won't notice a sizable performanace difference. The first of the three solutions presented here is the cleanest and easiest to understand at first glance.
By using std::vector
, you don't need to worry about freeing the memory yourself and you don't need to worry about correctly destroying the dynamically allocated object when an exception causes a function to return early. In addition, a good implementation of the Standard Library containers (like the one provided with Visual C++) provides runtime checks in debug builds that help you to find common bugs like off-by-one errors or iterator invalidation errors.
Another method is to fill the buffer with zeros first, using memset
or std::fill
, before writing into it.
精彩评论