Understandably, going over a buffer errors out (or creates an overflow), but what happens if there are less than 12 bytes used in a 12 byte buffer? Is it possible or does the empty trailing always fill with 0s? Orthogonal question that may help: what is contained in a buffer when it is instantiated but not used by the application yet?
I have looked at a few pet programs in Visual Studio and it seems that they are appended with 0s (or null characters) but I am not sure if this is a MS implementation that may vary across language/ compiler.
ByteBuffer is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect() API on Buffer. Java Documentation of Byte Buffer has useful information.
1024 is the exact amount of bytes in a kilobyte. All that line means is that they are creating a buffer of 16 KB. That's really all there is to it. If you want to go down the route of why there are 1024 bytes in a kilobyte and why it's a good idea to use that in programming, this would be a good place to start.
Char buffers can be created either by allocation , which allocates space for the buffer's content, by wrapping an existing char array or string into a buffer, or by creating a view of an existing byte buffer. Like a byte buffer, a char buffer is either direct or non-direct.
Take the following example (within a block of code, not global):
char data[12]; memcpy(data, "Selbie", 6);
Or even this example:
char* data = new char[12]; memcpy(data, "Selbie", 6);
In both of the above cases, the first 6 bytes of data
are S
,e
,l
,b
,i
, and e
. The remaining 6 bytes of data
are considered "unspecified" (could be anything).
Is it possible or does the empty trailing always fill with 0s?
Not guaranteed at all. The only allocator that I know of that guarantees zero byte fill is calloc. Example:
char* data = calloc(12,1); // will allocate an array of 12 bytes and zero-init each byte memcpy(data, "Selbie");
what is contained in a buffer when it is instantiated but not used by the application yet?
Technically, as per the most recent C++ standards, the bytes delivered by the allocator are technically considered "unspecified". You should assume that it's garbage data (anything). Make no assumptions about the content.
Debug builds with Visual Studio will often initialize buffers with with 0xcc
or 0xcd
values, but that is not the case in release builds. There are however compiler flags and memory allocation techniques for Windows and Visual Studio where you can guaranteed zero-init memory allocations, but it is not portable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With