So here I believe I have a small buffer overflow problem I found when reviewing someone else\'s code. It immediately struck me as incorrect, and potentially dangerous, but a
The reason the string is printing fine in the debugger is that as part of the sprintf, the trailing NULL character is being written to memory (in this case beyond the buffer you allocated) and when it comes to reading the string the NULL character is present to terminate the string as expected.
The problem is that the byte containing the NULL character hasn't been allocated as part of the original new
and so could be used for a different allocation later. In this case, when you come to read the string afterwards you will likely get your original string with garbage appended.
Yes, you are correct. The buffer allocated will be 2 bytes too small to hold the string.
Since this is being allocated on the heap, it would be possible for this to result in a heap corruption. However, the liklihood of that depends on the what other allocations and releases of memory have occurred prior to this point and also on heap manager being used. See Heap Overflow for more.
Your real problem is that you're writing
char* buffer = new char[strlen("This string is 27 char long" + 1)];
instead of
char* buffer = new char[strlen("This string is 27 char long") + 1];
Meaning that on the first one you're giving strlen() an address which isn't the beginning of your string.
Try this code:
const char szText[] = "This string is 27 char long";
char* buffer = new char[strlen(szText) + 1];
sprintf(buffer, szText);
As stated by others, you are completely correct in assuming that this is no good, and the reason you don't see this is padding. Try valgrind
on this, this should definitively find that error.
Your assessment is correct. [edit] with the addition of the correction mentioned by James Curran.[/edit]
Likely, your test app didn't show the problem because the allocation is rounded up to the next multiple of 4, 8 or 16 (which are common allocation granularities).
This means you should be able to demonstrate with a 31 character long string.
Alternatively, use an "instrumenting" native memory profiler that can place guard bytes closely around such an allocation.
Many historic malloc
implementations put bookkeeping data immediately before and/or after the allocated block. It's possible that you're overwriting such data, in which case you would not see any error/crash until you try to free the memory (or perhaps free whatever the next block happens to be). Likewise, it's possible that the bookkeeping information for a subsequent allocation will later overwrite your string.
I suspect modern malloc
implementations make some effort to protect against heap corruption by padding allocations with integrity-check data, so if you're lucky, nothing bad will happen or you might get a warning message during a later allocation/free operation.