0

I am using systemC with visual C++ 2008. I wrote a simple hello world program. However I am getting this error repeatedly:

warning C4996: 'sprintf': This function or variable may be unsafe.

Why this is happening? I would appreciate any help.

1
  • It's a warning, not an error. Commented Jan 31, 2012 at 9:52

2 Answers 2

4

The compiler warns against sprintf() use because it may cause buffer overflow since it doesn't check buffer's limit. Instead, use snprintf() which never fills the buffer beyond the passed-in limit.

This advice is also given by the manpage:

Because sprintf() and vsprintf() assume an arbitrarily long string, callers must be careful not to overflow the actual space; this is often impossible to assure. Note that the length of the strings produced is locale-dependent and difficult to predict. Use snprintf() and vsnprintf() instead (or asprintf(3) and vasprintf(3)).

Sign up to request clarification or add additional context in comments.

2 Comments

"this is often impossible to assure" only if you're an idiot. People who have been coding in C for long enough know the difference between truly insecure stuff (like gets, or scanf("%s") where you don't control the input) and stuff like sprintf where you can make it safe. Everyone else should go back to using VB :-) I always turn off these warnings with a #define since I know what I'm doing.
I do agree that gets() and sprintf() fall into different categories when it comes to potential for vulnerabilities, but there is a danger in using sprintf() which you have not mentioned and which is connected with maintenance: it's easy to forget to update buffer size when you modify the format string or other parameters passed to sprintf().
0

It's insecure because - From MSDN

There is no way to limit the number of characters written, which means that code using sprintf is susceptible to buffer overruns. Consider using the related function _snprintf, which specifies a maximum number of characters to be written to buffer, or use _scprintf to determine how large a buffer is required. Also, ensure that format is not a user-defined string.

3 Comments

It's not insecure, it may be insecure.
Yes, it's only insecure if you don't know what you're doing.
@skeptic: "thanks everyone" is best expressed "by clicking on the check box outline to the left of the answer."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.