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.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
newbie
  • 4,639
  • 10
  • 32
  • 45

2 Answers2

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)).

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
  • "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. – paxdiablo Jan 28 '12 at 01:48
  • 3
    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()`. – Adam Zalcman Jan 28 '12 at 01:55
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.

Mahesh
  • 34,573
  • 20
  • 89
  • 115