Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

c - Can the input and output strings to sprintf() be the same?

I have used this type of convention many times in my code in the past:

strcpy ( cTmpA, "hello" );
sprintf ( cTmpA, "%s world", cTmpA );

Recently I switched my legacy C compiler to Visual Studio 2005, and found I got a garbled string resulting from the above code. It then occurred to me that perhaps the behaviour of sprintf() is not rigidly defined where one of the inputs matches the output string.

Is the above code valid K&R C? If not, how do I find all the places in my code where this type of call to sprintf() has occurred?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While it is valid K&R C, you probably want to rather know if it's valid POSIX - see sprintf Specification. We read:

If copying takes place between objects that overlap as a result of a call to sprintf() or snprintf(), the results are undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...