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.

strlen returns the length of the string without the null byte at the end. That means the actual storage requirement for your string is (strlen(string) + 1) and (strlen(stringaux) + 1).

See

man strlen

for more information.

you can check is the stack overflow causing the problem if you modify the code and use heap strings:

char *string;
char *stringaux;

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

or declare the both variables outside any function (including main) so they will be placed in data segment and not stack

your compiler could have option to insert stack overflow check code.

never use strcat() , use

snprintf(dest, sizeof(dest), "%s%s", dest, src) 

Instead.

No that’s even worse. You are reusing the dest in the same call. The result is indeterminate. If for some reason the implementation of snprintf decides internally to say put a NUL in the first byte before any copying is done, you have truncated one of the input strings.

If you were to use a different destination, that would be ok.

But this is a diversion from the OP’s query.