tags:

views:

184

answers:

3

Ok, I'm really confused by this behaviour in VS2008.

This code..

char data[512] = "";

char c[1] = "";
c[0] = '1';

strcat(data, c);

.. results in data being set to this string value: 1ÌÌÌÌhÿ

Surely it should just be 1?

How can I ensure data only contains the single char[] that I copy into it (i.e. 1)?

Why does strcat() copy all that garbage? Why does c even contain that garbage?

Thanks for any help

Edit: Thanks all.

+12  A: 

The problem here is that you are passing an invalid value to strcat. It expects the second parameter to be a valid c string value. To be valid it must be an array / pointer of char values which ends with a null terminator (\0). The value your are passing does not contain a null terminator and is hence invalid.

You need to define a null terminator for the string value c to be valid. For example

char c[2];
c[0] = '1';
c[1] = '\0';
JaredPar
+3  A: 

Because strcat() copies C-String. C-Strings are '\0' terminated. So when you copy 'c' it starts there than searches through memory until it finds a memory location containg '\0' then copies all this into data.

What you need to do is make sure that 'c' is a real C-String ('\0' terminated)

char c[2] = {};  // Sets all members to '\0';
c[0]      = '1'; // Sets c[0] to '1' but leaves c[1] as '\0'

// c Is still a C-string as it is a sequence terminated with a '\0' character.
Martin York
+3  A: 

No, it shouldn't be "just 1". Your c array is not a C-string, since you failed to zero-terminate it. When you pass something that is not a C-string to strcat, the behavior is undefined. This is what you observe in your case.

Note that it is simply impossible to squeeze a strung "1" into an array of size 1. You need array of at least 2 characters: one for '1' character and one for the zero-terminator character.

You can simply change your declaration of c to

char c[2] = ""; 

and the code will work as intended (the way I understand your intent).

AndreyT