-3

I've createed a buffer system, however determining a string read from a buffer is rather difficult compared to C#. Let's consider the following code that creates a char* to an array:

int Size = 6;
char* String = new char[ Size ]();

That'll create the pointer to a brand new array of a specified size. However, if I try to access an index outside of that size, an out of bounds error isn't shown:

String[ Size + 1 ];

Instead, for example I could "print" the array as if it were a string:

String[ 0 ] = 'S';
String[ 1 ] = 'T';
String[ 2 ] = 'R';
String[ 3 ] = 'I';
String[ 4 ] = 'N';
String[ 5 ] = 'G';
cout << String << endl;

However, this will not only print the characters within the original array but also random characters not within the original array, e.g. characters in indexes beyond the bounds of the array: (Example)

STRING&^%(^$$#%$*

Instead Of:

STRING

Why is this behavior happening and how can I avoid it?

user3519915
  • 129
  • 1
  • 3
  • 13

1 Answers1

4

The reason is that your string is not NUL terminated. Initialize Size to 7 and String[ 6 ] = '\0';

haccks
  • 104,019
  • 25
  • 176
  • 264
  • Ah! I didn't think that the string had to be null-terminated outside of my buffer, so that's where I messed up. I wonder why the down vote on my post though? It's a VERY valid question. – user3519915 Jun 04 '14 at 22:06
  • It did. For some reason SO said I had to wait 2 minutes before accepting it as an answer when I first saw the post. – user3519915 Jun 04 '14 at 22:41
  • The downvotes will be either because the question has dozens of duplicates, or because the question is too basic (or both). It's something you'd probably learn in Chapter 1 of a C book (although a modern C++ book which discourages the use of C-style arrays might not mention it early on). – M.M Jun 04 '14 at 22:50