Very Basic Char String Doubt.

I would like to have some confirmation to the following.

I'm compiling and running the following code without any apparent problems, but I reckon is not right, and could lead to experience problems, right? As the first line of code doesn't assign enough memory, to store five characters + a null character.

1
2
3
4
char *sAux = new char;
strcpy(sAux, "Hello");
cout << sAux;
delete sAux;


Instead the following should be more appropriate, is this correct?

1
2
3
4
char *sAux = new char[6];
strcpy(sAux, "Hello");
cout << sAux;
delete [] sAux;


Is it necessary to declare a string char of size six, given that the word is of size five, to give room for the extra null character?

Many thanks.
First code is wrong, and you have said why. That is a buffer overflow that fortunately isn't causing you issues in a small app, but would in a larger one.

The 2nd is correct. And yes you do need the null.

Also lookup memset();
OK, thanks, good to know I was understanding this right.

Just another clarification, would:
 
strcpy(sAux, "Hello");

automatically, add the '\0' character at the end of the string?
Or do I need to explicitly add it?
 
strcpy(sAux, "Hello\0");


I will look into memset();

Cheers!
"Hello" <-- includes already the zero character. That means you don't have to add \0. \0 defines the end of a string. If you fill a string character by character (dynamically) e.g.
1
2
3
4
5
char *my_string = new char[5];
my_string[0] = 72;
my_string[1] = 69;
my_string[2] = 76;
my_string[3] = 0;

you have to add a zero character to indicate the end of the strings for functions like cout, printf, ...
strings are nt really different to any normal array except that their end is indicated with a 0.
Topic archived. No new replies allowed.