[ale] C and segmentation fault

Lex Spoon sspoon at clemson.edu
Thu Jul 17 15:08:38 EDT 1997


Allocate the memory in writable space.  Also, be sure to allocate
enough space to hold the longer string in s1; in this case, it needs
space for at least 5 characters -- the 4 real characters S1S2 and
a terminating NUL character.

This should work (untested code):

main()
{
    char s1[BIGENOUGH];
    char s2[WHATEVER];

    strcpy(s1, "S1");
    strcpy(s2, "S2");
    strcat(s1,s2);

    printf("s1: %s\ns2: %s\n", s1, s2);
}


You could also use malloc (also untested):

main()
{
    char *s1;
    char *s2;

    s1 = malloc(10);  /* 10 characters is more than enough here; 
                         adjust as needed */
    strcpy(s1, "S1);
    s2 = "S2";       /* leave s2 in read-only memory */


    strcat(s1, s2);


    printf("s1: %s\ns2: %s\n", s1, s2);
}

For curiosity, you might try printing out the locations s1 and s2 in
the different versions by using printf's %p; you would likely see that
malloc, read-only strings, and stack-based arrays are all in distant
parts of memory.

By the way, there is a sprintf function you might investigate if you
are doing a bunch of string manipulation.
 
Finally, the library has a bunch of good books on C with stuff like
this.  :)


lex




> c_fowler at hotmail.com
> How can I join string S2 and S1 ont S1 so that s1 looks like 'S1S2'.
> 
> Thanks,
> Christopher Fowler
> 
> On 17-Jul-97 Tom Wiencko wrote:
> >c_fowler at hotmail.com wrote:
> >> 
> >> Why when I run this proggie do I get a segmentation fault?
> >> 
> >#include<stdio.h>
> >#include<string.h>
> >main()
> >{
> >        char *s1;
> >        char *s2;
> >        s1="S1";
> >        s2="S2";
> >        s2=strcat(s1,s2);
> >        return 0;
> >}
> >
> >Very simple.  The line "s2=strcat(s1,s2)" is causing strcat to
> >try to physically overwrite the read-only memory space where "S2"
> >lives.  When you assigned s2="S2" you are pointing s2 to an address
> >in an area where only constants are supposed to live.  You cannot
> >modify things in that address space.
> >
> >-Tom
> >----------------------------------------------------------------------
> >Tom Wiencko                                            tew at wiencko.com
> >President - Wiencko & Associates, Inc.






More information about the Ale mailing list