[ale] C and segmentation fault

Tom Wiencko tew at wiencko.com
Thu Jul 17 09:49:31 EDT 1997


c_fowler at hotmail.com wrote:
> 
> How can I join string S2 and S1 ont S1 so that s1 looks like 'S1S2'.
> 

Lots of ways, depending on exactly what you are doing in the larger
context of the program.  Here are a couple of thoughts:

...
        char *s1;
        char *s2;
	char s3[5]=""; /*memory allocated from stack and initialized*/
        s1="S1";
        s2="S2";
        strcat(s3,s1);
	strcat(s3,s2);
	s1=s3;         /* assign pointer s1 to space where s3 lives */
....
or
...
        char *s1;
        char *s2;
	char *s3;    
        s1="S1";
        s2="S2";
			/* memory allocated from heap */
	s3=(char *) malloc (strlen(s1)+strlen(s2)+1);
	strcat(s3,s1);
        strcat(s3,s2);
	s1=s3;          /* point s1 to newly allocated memory */
...

... among lots of other possibilities.  Recall also that you have 
allocated s1 as a pointer, not as real memory, so s1 does not "look
like" anything, but rather points to something that looks like
something.

Any better?

-Tom

----------------------------------------------------------------------
Tom Wiencko                                            tew at wiencko.com
President - Wiencko & Associates, Inc.






More information about the Ale mailing list