Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String going crazy if I don't give it a little extra room. Can anyone explain what is happening here?

First, I'd like to say that I'm new to C / C++, I'm originally a PHP developer so I am bred to abuse variables any way I like 'em.

C is a strict country, compilers don't like me here very much, I am used to breaking the rules to get things done.

Anyway, this is my simple piece of code:

char IP[15] = "192.168.2.1";
char separator[2] = "||";   

puts( separator );

Output:

||192.168.2.1

But if I change the definition of separator to:

char separator[3] = "||";

I get the desired output:

||

So why did I need to give the man extra space, so he doesn't sleep with the man before him?

like image 410
HyderA Avatar asked May 04 '11 11:05

HyderA


3 Answers

Strings in C are NUL-terminated. This means that a string of two characters requires three bytes (two for the characters and the third for the zero byte that denotes the end of the string).

In your example it is possible to omit the size of the array and the compiler will allocate the correct amount of storage:

char IP[] = "192.168.2.1";
char separator[] = "||";

Lastly, if you are coding in C++ rather than C, you're better off using std::string.

like image 21
NPE Avatar answered Nov 20 '22 18:11

NPE


That's because you get a not null-terminated string when separator length is forced to 2.

Always remember to allocate an extra character for the null terminator. For a string of length N you need N+1 characters.

Once you violate this requirement any code that expects null-terminated strings (puts() function included) will run into undefined behavior.

Your best bet is to not force any specific length:

char separator[] = "||";

will allocate an array of exactly the right size.

like image 52
sharptooth Avatar answered Nov 20 '22 17:11

sharptooth


If you're using C++ anyway, I'd recommend using the std::string class instead of C strings - much easier and less error-prone IMHO, especially for people with a scripting language background.

like image 13
Frank Schmitt Avatar answered Nov 20 '22 17:11

Frank Schmitt