11

I'm working on a C++ DDL, however I get the following issue in some places:

C4996 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 

I did try #define _CRT_SECURE_NO_WARNINGS, but the issue remains.
This is the code:

sprintf(szDebugString, "%s: 0x%x (%s%s%i)", ptrName, (DWORD)funcPtr, interfaceName, interfaceVersion.c_str(), i); 
1
  • Or just pass the /wd4996 option to cl. Commented Jul 7, 2018 at 5:31

5 Answers 5

15

You have to define _CRT_SECURE_NO_WARNINGS before #include <Windows.h>.

Alternatively, use the safe version:

sprintf_s(szDebugString, sizeof(szDebugString), "%s: 0x%x (%s%s%i)", ptrName, (DWORD)funcPtr, interfaceName, interfaceVersion.c_str(), i); 
Sign up to request clarification or add additional context in comments.

4 Comments

Or the one present in the standard: snprintf.
@MartinBonner Agreed; that is better, however I am unsure if it's available in Visual Studio.
Oh gah! See stackoverflow.com/questions/2915672/…. tl;dr? Not until VS2015. Only 16 years after a sensible set of semantics were standardized!
@MartinBonnersupportsMonica MS were very adamant at that semantics for internal reason. They also were offering different kind of ranged for loop. All because their interbal coding style
6

put this define into stdafx.h.

E.g.

#pragma once #define _CRT_SECURE_NO_WARNINGS #include "targetver.h" #include <stdio.h> #include <tchar.h> 

Comments

6

To turn off the warning for an entire project in the Visual Studio IDE:

1- Open the Property Pages dialog for your project.

2- Select the Configuration Properties > C/C++ > Advanced page.

3- Edit the Disable Specific Warnings property to add 4996. Choose OK to apply your changes.

2 Comments

you save me ( this was my first C++ project and you save me )
Thank you. The top answer doesn't work for my situation (sprintf() is being called by a library and it doesn't include Windows.h)
3

In my point of view, on a Windows project, it is not a good idea to disable the warning; a better idea is to improve the code. Mute the warning not just keeps this potential code vulnerability unnoticed, but also blinds programmers when introducing other potential code vulnerabilities.

Comments

0

From the docs:

You can turn off the warning for a specific line of code by using the warning pragma, #pragma warning(suppress : 4996). You can also turn the warning off within a file by using the warning pragma, #pragma warning(disable : 4996).

https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-3-c4996?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(C4996)%26rd%3Dtrue&view=vs-2017

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.