Results 1 to 3 of 3

Thread: segmentation fault in strcat()

  1. #1
    sankari27 NNTP User

    Default segmentation fault in strcat()

    Hello.

    My program gets "segmentation fault" in "strcat(string,stringaux)" and it is strange because I am sure that string always has space for adding the new stringaux due to before call strcat I check if size of the destiny plus new stringaux is less than string capacity:

    char string[100];
    char stringaux[3];

    void Function()
    {
    if ((strlen(string)+strlen(stringaux))<100)
    {
    strcat(string,stringaux)
    }
    }


    In this way strcat() never can make string be longer than 100. But still I get SEGMENTATION DEFAULT.

    I have been reading, and the explanation can be that the Stack gets full due to I have many local variables or ...

    Is there anybody can tell me some ideas about why SEGMENTATION DEFAULT is produced in strcat() when I am sure that is not because there is not space in the destiny string?

    Thanks in advance.

  2. #2

    Default Re: segmentation fault in strcat()

    I suspect you have oversimplified your code example.

    You should really write a complete program that we can copy from here, compile and run.

    I threw this together, it may help you.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void f(char *s, char *t)
    {
      if ( (strlen(s) + strlen(t) ) < 100) {
        printf ( "%s\n", s ) ;
        strcat(s,t) ;
        printf ( "%s\n", s ) ;
      } else {
        printf ( "Quack" ) ;
      }
    }
    
    int main () {
    # if 0
      /* Uninitialised strings contain who knows what ... */
      char s[100];
      char t[3];
    # else
      char s[] = "hello" ;
      char t[] = " world" ;
    # endif
    
      f(s,t) ;
    }

  3. #3

    Default Re: segmentation fault in strcat()

    Make sure all your strings are initialised before you try strlen() or strcat(), or else the results will be unpredictable.

    char s[] = "hello" ;
    will allocate 6 bytes, of which the last is the null char, value 0x00, used by strlen and strcat to identify the end of the string. If you don't initialise, you will have no control over where or whether the null character appears
    nb My poor rep is a bitcshlap for having dared to disagree with a moderator [oldcpu] over his howto, which should have had some fairly strong caveats. -15 points applied in 1 hit - moderator strength - for a personal disagreement, not a moderation issue.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •