Error c4996 localtime this function or variable may be unsafe

I am writing a simple logging class in C++ for learning purposes. My code contains a function that returns a string of today's date. However, I get a compiler error whenever 'localtime' is called. ...

I am writing a simple logging class in C++ for learning purposes. My code contains a function that returns a string of today’s date. However, I get a compiler error whenever ‘localtime’ is called.

std::string get_date_string(time_t *time) {
    struct tm *now = localtime(time);
    std::string date = std::to_string(now->tm_mday) + std::to_string(now->tm_mon) + std::to_string(now->tm_year);
    return date;
}

I have tried using #define _CRT_SECURE_NO_WARNINGS. It didn’t work and the same error appeared. I also tried putting _CRT_SECURE_NO_WARNINGS inside the preprocessor definitions in the project properties. This gave an unresolved external error.

Does anyone have any ideas on what to do?

asked Jun 26, 2016 at 0:04

ChiefHagno's user avatar

2

The problem is that std::localtime is not thread-safe because it uses a static buffer (shared between threads). Both POSIX and Windows have safe alternatives: localtime_r and localtime_s.

Here is what I do:

inline std::tm localtime_xp(std::time_t timer)
{
    std::tm bt {};
#if defined(__unix__)
    localtime_r(&timer, &bt);
#elif defined(_MSC_VER)
    localtime_s(&bt, &timer);
#else
    static std::mutex mtx;
    std::lock_guard<std::mutex> lock(mtx);
    bt = *std::localtime(&timer);
#endif
    return bt;
}

// default = "YYYY-MM-DD HH:MM:SS"
inline std::string time_stamp(const std::string& fmt = "%F %T")
{
    auto bt = localtime_xp(std::time(0));
    char buf[64];
    return {buf, std::strftime(buf, sizeof(buf), fmt.c_str(), &bt)};
}

answered Jun 26, 2016 at 0:26

Galik's user avatar

GalikGalik

46.4k4 gold badges81 silver badges114 bronze badges

1

Try to #define _CRT_SECURE_NO_WARNINGS before #include any other header files, like the following code

#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
//your code

answered Jun 26, 2016 at 2:44

Null's user avatar

NullNull

6492 gold badges6 silver badges15 bronze badges

1

Содержание

  1. Error c4996 localtime this function or variable may be unsafe
  2. Answered by:
  3. Question
  4. Answers
  5. All replies
  6. Предупреждение компилятора (уровень 3) C4996
  7. Комментарии
  8. Отключение предупреждения
  9. Отключение предупреждения для определенной строки кода
  10. Отключение предупреждения в файле
  11. Отключение предупреждения в сборках командной строки
  12. Отключение предупреждения для проекта в Visual Studio
  13. Отключение предупреждения с помощью макросов препроцессора
  14. Имена функций POSIX
  15. Небезопасные функции библиотеки CRT
  16. Небезопасные функции стандартной библиотеки
  17. Проверенные итераторы включены
  18. Небезопасный код MFC или ATL
  19. Устаревшие функции и переменные CRT
  20. Маршалинг ошибок в коде СРЕДЫ CLR
  21. Пример: определяемая пользователем нерекомендуемая функция
  22. Compiler Warning (level 3) C4996
  23. Remarks
  24. Turn off the warning
  25. Turn off the warning for a specific line of code
  26. Turn off the warning within a file
  27. Turn off the warning in command-line builds
  28. Turn off the warning for a project in Visual Studio
  29. Disable the warning using preprocessor macros
  30. POSIX function names
  31. Unsafe CRT Library functions
  32. Unsafe Standard Library functions
  33. Checked iterators enabled
  34. Unsafe MFC or ATL code
  35. Obsolete CRT functions and variables
  36. Marshaling errors in CLR code
  37. Example: User-defined deprecated function

Error c4996 localtime this function or variable may be unsafe

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

Hi,
how to resolve these

Many Thanks & Best Regards, Hua Min

Answers

how to resolve these
Error 2 error C2664: ‘errno_t localtime_s(tm *,const time_t *)’ : cannot convert argument 1 from ‘tm **’ to ‘tm *’ c:app2t1.h 266 1 DBServer

The message is clear enough: you’re passing a pointer to a pointer when you should be
passing just a pointer. Look at the examples in the documentation, and don’t just guess
at what to code.

struct tm * timeinfo;

struct tm timeinfo;

I include both time.h and ctime, but I still get these

how to resolve these

Do you have the required header included?

I include both time.h and ctime, but I still get these

Many Thanks & Best Regards, Hua Min

I include both time.h and ctime, but I still get these

>I include both time.h and ctime, but I still get these

Why did you include both? I said «or«. Use one OR the other.

>Error 2 error C4996: ‘localtime’: This function or variable may be unsafe

Since the compiler apparently is treating this as an error now rather than a warning,
why don’t you use what it says?

>Consider using localtime_s instead.

Источник

Предупреждение компилятора (уровень 3) C4996

Код использует функцию, член класса, переменную или определение типа, помеченную как нерекомендуемую. Символы устарели с помощью __declspec(deprecated) модификатора или атрибута C++14 [[deprecated]] . Фактическое предупреждающее сообщение C4996 задается модификатором или атрибутом deprecated объявления.

Это предупреждение всегда является преднамеренным сообщением автора файла заголовка, объявляющего символ. Не используйте устаревший символ без понимания последствий.

Комментарии

Многие функции, функции-члены, шаблоны функций и глобальные переменные в библиотеках Visual Studio устарели. Некоторые функции, такие как POSIX и функции Майкрософт, устарели, так как теперь они имеют другое предпочтительное имя. Некоторые функции библиотеки среды выполнения C устарели, так как они небезопасны и имеют более безопасный вариант. Другие нерекомендуемые, так как они устарели. Сообщения об устаревании обычно включают предполагаемую замену устаревшей функции или глобальной переменной.

Отключение предупреждения

Чтобы устранить проблему C4996, обычно рекомендуется изменить код. Вместо этого используйте предлагаемые функции и глобальные переменные. Если вам нужно использовать существующие функции или переменные по соображениям переносимости, можно отключить предупреждение.

Отключение предупреждения для определенной строки кода

Чтобы отключить предупреждение для определенной строки кода, используйте директиву warning pragma. #pragma warning(suppress : 4996)

Отключение предупреждения в файле

Чтобы отключить предупреждение в файле для всего следующего, используйте директиву pragma #pragma warning(disable : 4996) предупреждения.

Отключение предупреждения в сборках командной строки

Чтобы отключить предупреждение глобально в сборках командной строки, используйте параметр командной /wd4996 строки.

Отключение предупреждения для проекта в Visual Studio

Чтобы отключить предупреждение для всего проекта в интегрированной среде разработки Visual Studio, выполните следующие действия.

Откройте диалоговое окно «Страницы свойств » для проекта. Сведения об использовании диалогового окна «Страницы свойств» см. в разделе «Страницы свойств».

Выберите страницу свойств> конфигурацииC/C++>Advanced.

Измените свойство Disable Specific Warnings для добавления 4996 . Нажмите кнопку «ОК» , чтобы применить изменения.

Отключение предупреждения с помощью макросов препроцессора

Вы также можете использовать макросы препроцессора для отключения определенных классов предупреждений об устаревании, используемых в библиотеках. Эти макросы описаны ниже.

Чтобы определить макрос препроцессора в Visual Studio, выполните следующие действия.

Откройте диалоговое окно «Страницы свойств » для проекта. Сведения об использовании диалогового окна «Страницы свойств» см. в разделе «Страницы свойств».

Разверните свойства > конфигурации препроцессора C/C++>.

В свойстве «Определения препроцессора» добавьте имя макроса. Нажмите кнопку ОК для сохранения изменений, а затем выполните повторную сборку проекта.

Чтобы определить макрос только в определенных исходных файлах, добавьте строку, #define EXAMPLE_MACRO_NAME например перед любой строкой, включающей файл заголовка.

Ниже приведены некоторые распространенные источники предупреждений и ошибок C4996:

Имена функций POSIX

The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: new-name. See online help for details.

Корпорация Майкрософт переименовывает некоторые функции БИБЛИОТЕК POSIX и Microsoft в CRT в соответствии с ограничениями C99 и C++03 для зарезервированных и глобальных имен, определенных реализацией. Не рекомендуется использовать только имена, а не сами функции. В большинстве случаев в имя функции был добавлен символ подчеркивания, чтобы создать соответствующее имя. Компилятор выдает предупреждение об устаревании для исходного имени функции и предлагает предпочтительное имя.

Чтобы устранить эту проблему, мы обычно рекомендуем изменить код, чтобы использовать предлагаемые имена функций. Однако обновленные имена зависят от корпорации Майкрософт. Если вам нужно использовать существующие имена функций по причинам переносимости, эти предупреждения можно отключить. Функции по-прежнему доступны в библиотеке под их исходными именами.

Чтобы отключить предупреждения об устаревании для этих функций, определите макрос _CRT_NONSTDC_NO_WARNINGS препроцессора. Этот макрос можно определить в командной строке, включив параметр /D_CRT_NONSTDC_NO_WARNINGS .

Небезопасные функции библиотеки CRT

This function or variable may be unsafe. Consider using safe-version instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Корпорация Майкрософт не рекомендует использовать некоторые функции стандартной библиотеки CRT и C++, так как доступны более безопасные версии. Большинство устаревших функций позволяют отменить доступ на чтение или запись к буферам. Их неправильное использование может привести к серьезным проблемам безопасности. Компилятор выдает предупреждение об устаревании для этих функций и предлагает предпочтительную функцию.

Чтобы устранить эту проблему, рекомендуется использовать вместо нее функцию или переменную safe-version . Иногда невозможно, по соображениям переносимости или обратной совместимости. Тщательно убедитесь, что в коде невозможно перезаписать или перечитать буфер. Затем можно отключить предупреждение.

Чтобы отключить предупреждения об устаревании для этих функций в CRT, определите _CRT_SECURE_NO_WARNINGS .

Чтобы отключить предупреждения о нерекомендуемых глобальных переменных, определите _CRT_SECURE_NO_WARNINGS_GLOBALS .

Дополнительные сведения об этих устаревших функциях и глобальных функциях см. в разделе «Функции безопасности» в CRT и безопасных библиотеках: стандартная библиотека C++.

Небезопасные функции стандартной библиотеки

‘std:: function_name ::_Unchecked_iterators::_Deprecate’ Call to std:: function_name with parameters that may be unsafe — this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ ‘Checked Iterators’

В Visual Studio 2015 это предупреждение отображается в отладочных сборках, так как некоторые шаблоны функций стандартной библиотеки C++ не проверяют правильность параметров. Часто это связано с тем, что функции недостаточно информации для проверки границ контейнера. Или, поскольку итераторы могут использоваться неправильно с функцией. Это предупреждение помогает определить эти функции, так как они могут быть источником серьезных дыр в вашей программе. Дополнительные сведения см. в разделе «Проверенные итераторы».

Например, это предупреждение отображается в режиме отладки при передаче указателя std::copy на элемент вместо обычного массива. Чтобы устранить эту проблему, используйте соответствующий объявленный массив, чтобы библиотека может проверить экстенты массива и выполнить проверку границ.

В C++14 были обновлены несколько стандартных алгоритмов библиотеки с версиями «двойного диапазона». При использовании версий двойного диапазона второй диапазон обеспечивает необходимую проверку границ:

В этом примере показано несколько других способов использования стандартной библиотеки для проверки использования итератора, а также если флажок использования может быть опасным:

Если вы убедились, что код не может иметь ошибку переполнения буфера, вы можете отключить это предупреждение. Чтобы отключить предупреждения для этих функций, определите _SCL_SECURE_NO_WARNINGS .

Проверенные итераторы включены

C4996 также может возникнуть, если вы не используете проверяемый итератор, если _ITERATOR_DEBUG_LEVEL он определен как 1 или 2. По умолчанию для сборок в режиме отладки установлено значение 2, а для розничных сборок — значение 0. Дополнительные сведения см. в разделе «Проверенные итераторы».

Небезопасный код MFC или ATL

C4996 может возникнуть, если вы используете функции MFC или ATL, которые были нерекомендуемые по соображениям безопасности.

Чтобы устранить эту проблему, настоятельно рекомендуется изменить код для использования обновленных функций.

Сведения о том, как отключить эти предупреждения, см. в разделе _AFX_SECURE_NO_WARNINGS .

Устаревшие функции и переменные CRT

This function or variable has been superseded by newer library or operating system functionality. Consider using new_item instead. See online help for details.

Некоторые функции и глобальные переменные библиотеки устарели. Эти функции и переменные могут быть удалены в будущей версии библиотеки. Компилятор выдает предупреждение об устаревании для этих элементов и предлагает предпочтительную альтернативу.

Чтобы устранить эту проблему, рекомендуется изменить код на использование предлагаемой функции или переменной.

Чтобы отключить предупреждения об устаревании для этих элементов, определите _CRT_OBSOLETE_NO_WARNINGS . Дополнительные сведения см. в документации по устаревшей функции или переменной.

Маршалинг ошибок в коде СРЕДЫ CLR

C4996 также может возникать при использовании библиотеки маршалинга CLR. В этом случае C4996 является ошибкой, а не предупреждением. Эта ошибка возникает при marshal_as преобразовании между двумя типами данных, которым требуется marshal_context класс. Эту ошибку также можно получить, если библиотека маршалинга не поддерживает преобразование. Дополнительные сведения о библиотеке маршалинга см. в обзоре маршалинга в C++.

В этом примере возникает ошибка C4996, так как для библиотеки маршалинга требуется контекст для преобразования из a System::String в . const char *

Пример: определяемая пользователем нерекомендуемая функция

Атрибут можно использовать в собственном коде deprecated , чтобы предупреждать вызывающих объектов, если вы больше не рекомендуете использовать определенные функции. В этом примере C4996 создается в двух местах: одна для строки, в которой объявлена нерекомендуемая функция, и одна для строки, в которой используется функция.

Источник

Compiler Warning (level 3) C4996

Your code uses a function, class member, variable, or typedef that’s marked deprecated. Symbols are deprecated by using a __declspec(deprecated) modifier, or the C++14 [[deprecated]] attribute. The actual C4996 warning message is specified by the deprecated modifier or attribute of the declaration.

This warning is always a deliberate message from the author of the header file that declares the symbol. Don’t use the deprecated symbol without understanding the consequences.

Many functions, member functions, function templates, and global variables in Visual Studio libraries are deprecated. Some, such as POSIX and Microsoft-specific functions, are deprecated because they now have a different preferred name. Some C runtime library functions are deprecated because they’re insecure and have a more secure variant. Others are deprecated because they’re obsolete. The deprecation messages usually include a suggested replacement for the deprecated function or global variable.

The /sdl (Enable Additional Security Checks) compiler option elevates this warning to an error.

Turn off the warning

To fix a C4996 issue, we usually recommend you change your code. Use the suggested functions and global variables instead. If you need to use the existing functions or variables for portability reasons, you can turn off the warning.

Turn off the warning for a specific line of code

To turn off the warning for a specific line of code, use the warning pragma, #pragma warning(suppress : 4996) .

Turn off the warning within a file

To turn off the warning within a file for everything that follows, use the warning pragma, #pragma warning(disable : 4996) .

Turn off the warning in command-line builds

To turn off the warning globally in command-line builds, use the /wd4996 command-line option.

Turn off the warning for a project in Visual Studio

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

Open the Property Pages dialog for your project. For information on how to use the Property Pages dialog, see Property Pages.

Select the Configuration Properties > C/C++ > Advanced property page.

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

Disable the warning using preprocessor macros

You can also use preprocessor macros to turn off certain specific classes of deprecation warnings used in the libraries. These macros are described below.

To define a preprocessor macro in Visual Studio:

Open the Property Pages dialog for your project. For information on how to use the Property Pages dialog, see Property Pages.

Expand Configuration Properties > C/C++ > Preprocessor.

In the Preprocessor Definitions property, add the macro name. Choose OK to save, and then rebuild your project.

To define a macro only in specific source files, add a line such as #define EXAMPLE_MACRO_NAME before any line that includes a header file.

Here are some of the common sources of C4996 warnings and errors:

POSIX function names

The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: new-name. See online help for details.

Microsoft renamed some POSIX and Microsoft-specific library functions in the CRT to conform with C99 and C++03 constraints on reserved and global implementation-defined names. Only the names are deprecated, not the functions themselves. In most cases, a leading underscore was added to the function name to create a conforming name. The compiler issues a deprecation warning for the original function name, and suggests the preferred name.

To fix this issue, we usually recommend you change your code to use the suggested function names instead. However, the updated names are Microsoft-specific. If you need to use the existing function names for portability reasons, you can turn off these warnings. The functions are still available in the library under their original names.

To turn off deprecation warnings for these functions, define the preprocessor macro _CRT_NONSTDC_NO_WARNINGS . You can define this macro at the command line by including the option /D_CRT_NONSTDC_NO_WARNINGS .

Unsafe CRT Library functions

This function or variable may be unsafe. Consider using safe-version instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Microsoft deprecated some CRT and C++ Standard Library functions and globals because more secure versions are available. Most of the deprecated functions allow unchecked read or write access to buffers. Their misuse can lead to serious security issues. The compiler issues a deprecation warning for these functions, and suggests the preferred function.

To fix this issue, we recommend you use the function or variable safe-version instead. Sometimes you can’t, for portability or backwards compatibility reasons. Carefully verify it’s not possible for a buffer overwrite or overread to occur in your code. Then, you can turn off the warning.

To turn off deprecation warnings for these functions in the CRT, define _CRT_SECURE_NO_WARNINGS .

To turn off warnings about deprecated global variables, define _CRT_SECURE_NO_WARNINGS_GLOBALS .

For more information about these deprecated functions and globals, see Security Features in the CRT and Safe Libraries: C++ Standard Library.

Unsafe Standard Library functions

‘std:: function_name ::_Unchecked_iterators::_Deprecate’ Call to std:: function_name with parameters that may be unsafe — this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ ‘Checked Iterators’

In Visual Studio 2015, this warning appears in debug builds because certain C++ Standard Library function templates don’t check parameters for correctness. Often it’s because not enough information is available to the function to check container bounds. Or, because iterators may be used incorrectly with the function. This warning helps you identify these functions, because they may be a source of serious security holes in your program. For more information, see Checked iterators.

For example, this warning appears in Debug mode if you pass an element pointer to std::copy , instead of a plain array. To fix this issue, use an appropriately declared array, so the library can check the array extents and do bounds checking.

Several standard library algorithms were updated to have «dual range» versions in C++14. If you use the dual range versions, the second range provides the necessary bounds checking:

This example demonstrates several more ways the standard library may be used to check iterator usage, and when unchecked usage may be dangerous:

If you’ve verified that your code can’t have a buffer-overrun error, you can turn off this warning. To turn off warnings for these functions, define _SCL_SECURE_NO_WARNINGS .

Checked iterators enabled

C4996 can also occur if you don’t use a checked iterator when _ITERATOR_DEBUG_LEVEL is defined as 1 or 2. It’s set to 2 by default for debug mode builds, and to 0 for retail builds. For more information, see Checked iterators.

Unsafe MFC or ATL code

C4996 can occur if you use MFC or ATL functions that were deprecated for security reasons.

To fix this issue, we strongly recommend you change your code to use updated functions instead.

For information on how to suppress these warnings, see _AFX_SECURE_NO_WARNINGS .

Obsolete CRT functions and variables

This function or variable has been superseded by newer library or operating system functionality. Consider using new_item instead. See online help for details.

Some library functions and global variables are deprecated as obsolete. These functions and variables may be removed in a future version of the library. The compiler issues a deprecation warning for these items, and suggests the preferred alternative.

To fix this issue, we recommend you change your code to use the suggested function or variable.

To turn off deprecation warnings for these items, define _CRT_OBSOLETE_NO_WARNINGS . For more information, see the documentation for the deprecated function or variable.

Marshaling errors in CLR code

C4996 can also occur when you use the CLR marshaling library. In this case, C4996 is an error, not a warning. The error occurs when you use marshal_as to convert between two data types that require a marshal_context Class. You can also receive this error when the marshaling library doesn’t support a conversion. For more information about the marshaling library, see Overview of marshaling in C++.

This example generates C4996 because the marshaling library requires a context to convert from a System::String to a const char * .

Example: User-defined deprecated function

You can use the deprecated attribute in your own code to warn callers when you no longer recommend use of certain functions. In this example, C4996 is generated in two places: One for the line the deprecated function is declared on, and one for the line where the function is used.

Источник

Kastlex

0 / 0 / 0

Регистрация: 17.02.2015

Сообщений: 3

1

17.02.2015, 18:00. Показов 12258. Ответов 6

Метки нет (Все метки)


студия 13 ругается на функцию

C++
1
2
time_t t = time(0);
    tm *lt = localtime(&t);

и сама ошибка: Ошибка 1 error C4996: ‘localtime’: This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.

собственно, рекомендации компилятора я выполнил

C++
1
#define _CRT_SECURE_NO_WARNINGS

но ошибка остается, что делать?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

17.02.2015, 18:04

2

В свойствах проекта поставь «обрабатывать предупреждения как ошибки» — нет.



0



0 / 0 / 0

Регистрация: 17.02.2015

Сообщений: 3

17.02.2015, 18:10

 [ТС]

3

вот так на данный момент, ошибка сохраняется

Миниатюры

'localtime': This function or variable may be unsafe
 



0



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

17.02.2015, 18:14

4

Ошибка или предупреждение?



0



0 / 0 / 0

Регистрация: 17.02.2015

Сообщений: 3

17.02.2015, 18:15

 [ТС]

5

да ошибка, я ведь написал, думал дело в том, что распознает предупреждения как ошибки, но нет, не в этом



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

17.02.2015, 19:27

6

Цитата
Сообщение от Kastlex
Посмотреть сообщение

#define _CRT_SECURE_NO_WARNINGS

Это надо писать до подключения всех заголовочных файлов. Иначе не будет работать



2



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

17.02.2015, 19:39

7

С отключенной обработкой предупреждений должно без этой строки работать.



0



  • Remove From My Forums
  • Question

  • Hi,
    how to resolve these

    Error 2 error C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:dp11dbserver 150927dbserverbayertree.h 264 1 DBServer
    Error 3 error C3861: 'time': identifier not found c:app2t1.h 263 1 DBServer
    Error 4 error C3861: 'localtime': identifier not found c:app2t1.h 264 1 DBServer
    Error 5 error C3861: 'strftime': identifier not found c:app2t1.h 266 1 DBServer

    due to these

    258  t00.open("c:\00.txt");
    259  time_t rawtime;
    260  struct tm * timeinfo;
    261  char buffer[80];
    262
      time(&rawtime);
      timeinfo = localtime(&rawtime);
    
    
      strftime(buffer, 80, "%d-%m-%Y %I:%M:%S", timeinfo);
      std::string str(buffer);
    
    
      //
      t00 << str;
    
    
      t00.close();


    Many Thanks & Best Regards, Hua Min

Answers

  • how to resolve these
    Error 2
    error C2664: ‘errno_t localtime_s(tm *,const time_t *)’ : cannot convert argument 1 from ‘tm **’ to ‘tm *’
    c:app2t1.h 266
    1 DBServer

    err = localtime_s(&timeinfo, &rawtime);

    The message is clear enough: you’re passing a pointer to a pointer when you should be

    passing just a pointer. Look at the examples in the documentation, and don’t just guess
    at what to code.

    Change:

    struct tm * timeinfo;

    to:

    struct tm timeinfo;

    — Wayne

    • Proposed as answer by

      Monday, November 30, 2015 8:11 AM

    • Marked as answer by
      May Wang — MSFT
      Monday, December 7, 2015 9:49 AM

  • I include both time.h and ctime, but I still get these

    Error	2	error C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.	c:app2t1.h	266	1	DBServer
    Error	3	error C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.	c:app2t1.h	266	1	DBServer

    If you don’t want to change functions, look up the C4996 message to learn several different ways to suppress it.

    • Proposed as answer by
      May Wang — MSFT
      Monday, November 30, 2015 8:11 AM
    • Marked as answer by
      May Wang — MSFT
      Monday, December 7, 2015 9:49 AM

2 Августа 2017

Время чтения: 5 минут

Visual Studio unsafe error скриншот

Компилятор в Visual Studio сильно отличается от привычных большинству программистов GCC или CLANG, из-за чего при написании кода на C или C++ очень часто возникают неожиданные проблемы в виде ошибки использования стандартных функций, например, scanf, fopen, sscanf и тому подобным. Студия предлагает заменять функции на безопасные (повезёт, если нужно просто добавить _s к функции с ошибкой, но нередко в этих функциях идёт иной набор аргументов, нежели в обычной программе). Если вы не готовы с этим мириться, то этот пост для вас!

Давайте для начала создадим обычный консольный проект в Visual Studio и напишем простенькую программу, которая запрашивает ввод двух чисел, вводит их и затем выводит на экран.

#include "stdafx.h"
#include <stdio.h>

int main() {
	int a, b;

	printf("Enter a: ");
	scanf("%d", &a);

	printf("Enter b: ");
	scanf("%d", &b);

	printf("a: %d, b: %dn", a, b);
	return 0;
}

Попробовав выполнить сборку проекта, обнаружим те самые ошибки.

Чтобы Visual Studio не тратила ваши нервы, сделаем следующее:

1. Выберем пункт «Проект» в верхнем меню

2. В открывшемся списке щёлкнем по «Свойства название_проекта»

Программа, вводящая два числа и выводящая их

Программа, вводящая два числа и выводящая их

Ошибка компиляции из-за небезопасности функций

Ошибка компиляции из-за небезопасности функций

Проект -> Свойства {навание проекта}

Проект — Свойства {навание проекта}

3. В появившемся окне выберем Свойства конфигурации, C/C++, Препроцессор

4. В строке Определения препроцессора допишем в самый конец строку ;_CRT_SECURE_NO_WARNINGS

5. Нажмём ОК

Свойства конфигурации

Свойства конфигурации

Определения препроцессора

Определения препроцессора

OK

Нажимаем OK

6. Попробуем заново выполнить сборку проекта:

Успешная сборка проекта

Успешная сборка проекта

Ошибки исчезли, сборка прошла успешно и программа прекрасно работает! Теперь можно писать код как обычно, не переживая о необычном поведении Visual Studio!

Фото Перминова Андрея, автора этой статьи

Программист, сооснователь programforyou.ru, в постоянном поиске новых задач и алгоритмов

Языки программирования: Python, C, C++, Pascal, C#, Javascript

Выпускник МГУ им. М.В. Ломоносова

I create a basic program using asctime in Visual studio 2015.
The following error message occurred when trying to compose based on the format and description.
Looking at the error message, the compiler has detected an unused declaration.
I would like to know the cause and how to deal with it.

Before correction

Error C4996
'localtime': This function or variable may be unsafe.
Consider using localtime_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
See online help for details.
Error C4996
'asctime': This function or variable may be unsafe.
Consider using asctime_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
See online help for details.</Code></pre>
<p><br />
After correction<br />
In addition to the above errors, the following warnings have been increased.</p>
<pre><code>warning
C4005 '_CRT_NONSTDC_NO_WARNINGS': Macro has been redefined.

source code:

Before correction

# include "stdafx.h"
#include&lt;stdlib.h&gt;
#include&lt;stdio.h&gt;
#include&lt;time.h&gt;
int main ()
{
    time_t jikoku;
    struct tm * ltime;

    time (&amp;jikoku);
    ltime = localtime (&amp;jikoku);
    printf ("% s", asctime (ltime));
    system ("pause");
    return 0;
}

After correction

# include "stdafx.h"
#include&lt;stdlib.h&gt;
#include&lt;stdio.h&gt;
#include&lt;time.h&gt;
#define _CRT_NONSTDC_NO_WARNINGS
int main ()
{
    time_t jikoku;
    struct tm * ltime;

    time (&amp;jikoku);
    ltime = localtime (&amp;jikoku);
    printf ("% s", asctime (ltime));
    system ("pause");
    return 0;
}

Try it

#define _CRT_NONSTDC_NO_WARNINGS

I compiled the above settings and compiled, but I got the same error

information:(language/FW/tool version etc.)

Language
C
Environment
Windows 7 Professional
Tool
Microsoft Visual Studio Community 2015
Version 14.0.25420.01 Update3

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error c4996 getch
  • Error c4996 fopen this function or variable may be unsafe
  • Error c4716 должна возвращать значение
  • Error c4703 используется потенциально неинициализированная локальная переменная указатель
  • Error c4700 использована неинициализированная локальная переменная

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии