Why does the compiler still warn me about unsafe strtok even after I define _CRT_SECURE_NO_WARNINGS?
Asked Answered
H

4

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?

Heiner answered 10/1, 2014 at 12:16 Comment(4)
There is no question and no sense at all. Why not simply using strtok_s ? What's the problem ?Carolincarolina
Your #define should in any case be before #include "stdafx.h" or alternatively put it in your project properties under C++/Preprocessor definitions.Forzando
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.Harrisharrisburg
@Carolincarolina Because strtok_s is a proprietary library extension and thus not portable.External
C
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>
Congruence answered 10/1, 2014 at 13:36 Comment(0)
H
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.

Hist answered 8/12, 2016 at 9:30 Comment(0)
M
2

Try following.

#pragma warning (disable : 4996)

Note the error number is C4996.

Mciver answered 12/6, 2018 at 4:24 Comment(0)
P
-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

Protolanguage answered 10/1, 2014 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.