6

I am using Visual Studio Express 2012 for Windows Desktop.

I always get error

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

When I try to build the following:

#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char the_string[81], *p;
    cout << "Input a string to parse: ";
    cin.getline(the_string, 81);
    p = strtok(the_string, ",");
    while (p != NULL) {
        cout << p << endl;
        p = strtok(NULL, ",");
    }
    system("PAUSE");
    return 0;
}

Why am I getting this error even though I define _CRT_SECURE_NO_WARNINGS, and how do I fix it?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • There is no question and no sense at all. Why not simply using `strtok_s` ? What's the problem ? – Blacktempel Jan 10 '14 at 12:18
  • 1
    Your `#define` should in any case be *before* `#include "stdafx.h"` or alternatively put it in your project properties under C++/Preprocessor definitions. – Roger Rowland Jan 10 '14 at 12:19
  • The solution is to 1) read the details in the online help, and 2) use `strtok_s` instead, as suggested - or use C++ functions instead of C. Do *not* switch off warnings. – molbdnilo Jan 10 '14 at 13:00
  • @Blacktempel Because `strtok_s` is a proprietary library extension and thus not portable. – ComicSansMS Jan 10 '14 at 13:51

4 Answers4

7

Your #define doesn't work because of the content of your precompiled header file (stdafx.h). The boilerplate one looks like this:

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

It is the last two #includes that cause the problem, those .h files themselves already #include string.h. Your #define is therefore too late.

Beyond defining the macro in the compiler settings instead, the simple workaround is to just move the #define into your stdafx.h file. Fix:

#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
6

This may be an old post but I had a similar problem recently. I went into the project options -> C/C++ -> Preprocessor -> added _CRT_SECURE_NO_WARNINGS to the list of Preprocessor Definitions. This way you don´t have to put it in every file.

Martin
  • 61
  • 1
  • 1
2

Try following.

#pragma warning (disable : 4996)

Note the error number is C4996.

getsuha
  • 711
  • 6
  • 16
-1

It looks like you switched on a compiler option that forces the compiler to consider all warnings as errors. Either switch off this option or indeed use macro _CRT_SECURE_NO_WARNINGS

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335