Home > front end >  Is this unsafe to use in C?
Is this unsafe to use in C?

Time:11-16

Hello I've come upon a problem. Im not very experienced in C.

I am trying to concatenate one char to my path variable.

But when I am running this line of code my other string variable gets "overriden" or behaves weird afterwards. When commented out everything works normally. I don't want to post the whole code here inseat I am just curios if this single line is somehow unsafe to run.

strcat(path, "/");

I also tried:

//edit i actually tried strcat but later strncat copied the line while reversing the changes//

char temp = '/';
strncat(path, &temp);

I am stuck wayyy to long on this so maybe someone can help.

CodePudding user response:

For starters the function strncat has three parameters

char *strncat(char * restrict s1, const char * restrict s2, size_t n);

So this call

strncat(path, "/");

will not compile.

Apart from this error this code snippet

char temp = '/';
strncat(path, &temp);

has one more error that is the expression &temp does not point to a string.

You can append a character to a string only if the array containing the string has enough space to accommodate one more character. For example you may not change a string literal.

If the array containing the string has enough memory to accommodate the character '/' then you can write

strcat( path, "/" );

or

size_t n = strlen( path );
path[n  ] = '/';
path[n] = '\0';

Or as @Barmar correctly pointed in his comment to the answer you could use strncat the following way

char temp = '/';
strncat(path, &temp, 1);
  • Related