[英]sprintf vs strcat for appending string
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.
在我的测试中确实如此,但是我不想在某些情况下破坏代码的功能。
You should use strcat
with a sufficiently large destination array. 您应该将
strcat
与足够大的目标数组一起使用。
Using sprintf
with the same array as destination and a string argument for %s
has undefined behavior. 将
sprintf
与目标数组相同,并将字符串参数用作%s
具有未定义的行为。 Most existing implementations will produce the expected result for the specific case in the question, but the C Standard make it explicitly undefined. 大多数现有的实现将为问题中的特定情况产生预期的结果,但是C标准使其明确未定义。
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. 这意味着参数3与参数1指向的数组重叠,如果参数3指向的数组被取消引用,这是不正确的,因为它会别名通过参数1取消引用的内存,该参数在
sprintf
原型中被声明为restrict
指针,这意味着任何其他指针都不应读取或写入通过它访问的内存。
A corner case such as sprintf(someString, "%.0s%s", someString, someOtherString);
角落情况,例如
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. 如果
someOtherString
符合someString
, someString
定义行为,因为未取消引用参数3,但编译器仍可能发出警告。
Using sprintf
to print into the same string as one of the sources is undefined behavior. 使用
sprintf
打印为与源之一相同的字符串是未定义的行为。 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. 您可以使用
sprintf
来打印到第三个字符串,但是无论如何strcat
都将具有更高的性能,因为它不必解析格式字符串并进行额外的复制。 In both cases, it is up to you to ensure that there is sufficient space in someString
to fit contents of someOtherString
. 在这两种情况下,您都需要确保
someString
中有足够的空间来容纳someOtherString
内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.