Consider the following program segment :#include #include void main () { char buf[100] = "hello"; strcat(buf,buf); printf(buf);}While executing this in VC++ I do not get an output . Looks like the program runs into an infinite loop. But while executing the same in Turbo C I get the output as "hellohelloh". What could be the reason behind this difference in output?

Questions by dhana80s

Showing Answers 1 - 7 of 7 Answers

uddin2000

  • Sep 13th, 2006
 

It is complier depended. In vc++ workspace, we get an exception as buf is assigned an array of 100, strcat function assumes that the target has enough memory to copy the source into the target, where as in the above program we are trying to copy an buffer of size 100,into an buffer which has already 100 characters into it,there lies the problem

kbjarnason

  • Jul 1st, 2010
 

Consider how strcat might be written:

strcat( char *dst, char *src )
{
   /* Find end of string */
   while ( *dst )
        dst++;

   while ( *src )
      *dst++ = *src++;
}

Basically, this reads a character from src, writing it to dst, until the value read from src is 0 - i.e. end of source string.

Let's try it with a short example:

char buff[100] = "Hi";

buff now contains three useful values: 'H', 'i' and '', which terminates the string.  The first thing our strcat does is finds the 0, because that's where the next character should go if we're "cat"ing the string.

What do we do now?  We read from src.  src points to the 'H'.  We read the 'H', we write it out to... er... we writ it out where the used to be.  We just destroyed the very thing that tells us where the string ends... so we're going to loop, either forever, or until the OS detects we've overrun our buffer and we crash.

The function you want here is memmove; it's a little more complicated to use, but unlike most of the other memory/string operations, it's actually designed to be used when the source and destination overlap, as they do in your example.

As kbjarneson pointed out, the problem is that you are clobbering the 0 terminator of the input string; once that happens, strcat() doesn't know where to stop.  His solution is to use memmove; however, you could also use strncat():

<pre>
size_t buflen = strlen(buf);
strncat(buf, buf, buflen);
</pre>

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions