Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...