segmentation fault in strcat()


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)

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.

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.

#include <stdio.h>
#include <string.h>

void f(char *s, char *t)
  if ( (strlen(s) + strlen(t) ) < 100) {
    printf ( "%s
", s ) ;
    strcat(s,t) ;
    printf ( "%s
", 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) ;

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