Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf vs strcat for appending string

Tags:

c

I have the following line:

  sprintf(someString,"%s%s",someString,someOtherString);

The compiler is giving me the following warning:

//someFile.c:277:15: error: passing argument 1 to restrict-qualified parameter aliases with argument 3 [-Werror=restrict]

I want to replace the line with something that won't give me a compile error. I googled the error and learned about restricted pointers and this was my solution:

strcat(someString, someOtherString);

Does this provide the same functionality? It does in my testing, but I don't want to break the code's functionality with some edge case.

like image 843
user3586940 Avatar asked Dec 23 '25 00:12

user3586940


2 Answers

Using sprintf to print into the same string as one of the sources is undefined behavior. You could sprintf to print into a third string but strcat will be more performant anyway as it doesn't have to parse the format string and do the extra copy. In both cases, it is up to you to ensure that there is sufficient space in someString to fit contents of someOtherString.

like image 92
Kon Avatar answered Dec 24 '25 14:12

Kon


You should use strcat with a sufficiently large destination array.

Using sprintf with the same array as destination and a string argument for %s has undefined behavior. Most existing implementations will produce the expected result for the specific case in the question, but the C Standard make it explicitly undefined.

The compiler rightfully complains with a warning that may be hard to decipher:

passing argument 1 to restrict-qualified parameter aliases with argument 3

This means that argument 3 overlaps with the array pointed to by argument 1, which is incorrect if the array pointed to by argument 3 is dereferenced because it would alias memory dereferenced through argument 1 which is declared as a restrict pointer in sprintf prototype, implying that no other pointer should read or write memory that is accessed through it.

A corner case such as sprintf(someString, "%.0s%s", someString, someOtherString); has defined behavior if someOtherString fits in someString because argument 3 is not dereferenced but the compiler might still issue the warning.

like image 33
chqrlie Avatar answered Dec 24 '25 12:12

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!