Re: help in this string concatenation by Scott
Scott
Sat May 07 08:08:35 CDT 2005
KRM_SW wrote:
> Hi,
>
> I am new to programming. I am trying to implement string concatenation. I
> use VC++. What's wrong with the following program?
> ----
>
> #include "stdafx.h"
> int main(int argc, char* argv[])
> {
>
> char *s = "i love you";
> char *t = "more than anything";
>
> while (*s != '\0')
> s++;
>
> while (*s++ = *t++)
> ;
> printf("%s\n", s);
> return 0;
> }
> ---
> it always gives me segmentation fault.
>
> Could anyone help me out?
>
> Thanks a lot,
> krm
There are several problems.
The s array is not long enough to contain the intended result. So if
you could append to it you would actually be stepping on some other
memory, with nasty results. You must allocate some memory before you
put something into it~!
In this case, the s array is constant and is probably stored in a region
of static memory that is write protected. You have no business writing
to a compile time constant!!
The above problems would be solved if you allocate a roomy buffer to
work in, like char v[100].
Finally, if the copy is successfull it has left the s pointer
incremented to the end of the string. You then pass that pointer to
printf, sort of optimistically hoping it knows where the start of the
string is. :)
--
Scott McPhillips [VC++ MVP]