10

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);
tambre
  • 4,625
  • 4
  • 42
  • 55
Joakim Carlsson
  • 1,540
  • 5
  • 19
  • 42

5 Answers5

13

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);
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
5

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.

david
  • 465
  • 5
  • 11
4

put this define into stdafx.h.

E.g.

#pragma once
#define _CRT_SECURE_NO_WARNINGS

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
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.

Amit G.
  • 2,546
  • 2
  • 22
  • 30
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

Zach Bloomquist
  • 5,309
  • 29
  • 44