Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this unsafe to use in C?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading