Меню

C4996 c ошибка sprintf

I am working on a UDP socket program in windows visual studio.
I am getting an error for sprintf statement. How to correct it?
My code is:

    for (i = 0; i < 30;i++) //take-off
{
    printf("send AT*REF:take offn");
            sprintf(command, "AT*REF=%d,290718208r", seq++);



    rc = sendto(sd, command, strlen(command) + 1, flags, (struct sockaddr *) &droneAddr, sizeof(droneAddr));
    if (rc<0) {
        printf("%s: can not send datan", argv[0]);
            return(1);
                    }
     }

The errors I am getting are :

Error   1 error C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
Error   1 error LNK2019: unresolved external symbol __imp__bind@12
Error   2 error LNK2019: unresolved external symbol __imp__htonl@4 referenced in function _main 
Error   3 error LNK2019: unresolved external symbol __imp__htons@4
Error   4 error LNK2019: unresolved external symbol __imp__sendto@24
Error   5 error LNK2019: unresolved external symbol __imp__socket@12
Error   6 error LNK2019: unresolved external symbol __imp__gethostbyname@4
Error   7 error LNK1120: 6 unresolved externals 

[error C4996: ‘sprintf’: This function or variable may be unsafe. 】Solution

@[TOC]

turn

Visual Studio 2013 compilation error [error C4996: ‘sprintf’: This function or variable may be unsafe.] solution

March 20, 2017 20:48:13

Green squat

Reading number: 6052
Collapse

																				<div class="tags-box space">
							<span class="label">Personal Classification:</span>
															 <a class="tag-link" href="https://blog.csdn.net/ture_dream/article/category/6412766" target="_blank">C++ Programming </a>
						</div>
																							</div>
			<div class="operating">
								</div>
		</div>
	</div>
 </div> (write the custom directory title here)

Compile the C++ language project in VS 2013. If you use the sprintf function, you will get the following error when compiling:

Error 5 error 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. F:C++HECHENHECHENFE.cpp 13 1 HECHEN

The reason is that Visual C++ 2013 uses more secure run-time library routines. New Security CRT functions (those with the «_s» suffix), see:

《Security-enhanced version of the CRT function》

The solution to this problem is given below:

Method 1: Replace the old old function with the new Security CRT functions.

Method 2: Mask this warning with the following method:

1. In the precompiled header file stdafx.h (note: be sure to include any header files before) define the following macro:

       #define _CRT_SECURE_NO_DEPRECATE

2. or declare#param warning(disable:4996)

3. Change the preprocessing definition:

Project -> Properties -> Configuration Properties -> C / C + + -> Preprocessor -> Preprocessor definition, add:

            _CRT_SECURE_NO_DEPRECATE


Reference material:Security template overload》

Intelligent Recommendation

More Recommendation

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

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

  • Remove From My Forums
  • Question

  •   Now I know that print formatting is available through stream operators, but how can this be used when printing to strings- i cant find anything in std::string (or am I missing something) and I presume there is no inherent method of using string << int etc. Any ideas?

    Thanks

Answers

  • Current compiler (and RTM one) not only prints that the function is deprecated, it also prints «safe» function that can be used instead.

    It suggests using sprintf_s() instead of sprintf().

    Example:

        #include <stdio.h>
        #include <stdlib.h>

        char* test (char *buffer, size_t length, int n)
        {
            sprintf (buffer, «%d», n);
            return buffer;
        }

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50712 for 80×86
    Copyright (C) Microsoft Corporation.  All rights reserved.

    z.cpp
    z.cpp(6) : warning C4996: ‘sprintf’ was declared deprecated
            C:Program FilesMicrosoft Visual Studio 8VCINCLUDEstdio.h(345) : see declaration of ‘sprintf’
            Message: ‘This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.’

    Thanks,
    Eugene

  • Have you tried using sprintf_s instead?

    Thanks,
       Ayman Shoukry
       VC++

For the specific case of getenv, it is indeed not reentrant or thread safe. As for why Microsoft doesn’t just replace it, you can’t take that interface and make it reentrant (you can almost make it «thread safe» with thread local storage, but it would still not be reentrant).

Even if you just took getenv away altogether, there is still the problem that you have the environ variable which would require some serious compiler level support to make thread safe, since it is just data.

Really, using environment variables for anything other than «setting it up before the process starts or at process start, and only reading from it from that point on» is going to probably end in tears if you have more than one thread. setenv and putenv don’t have a rich enough interface to express something like «set this set of environment variables atomically» and likewise getenv doesn’t have a way to express «read this set of environment variables atomically».

_dupenv_s is somewhat silly in my opinion, because if using that suddenly makes your code safe, it could probably done in a safe way with getenv. _dupenv_s solves a tiny subset of the problems with using environment variables in a multithreaded scenario.

For the specific case of getenv, it is indeed not reentrant or thread safe. As for why Microsoft doesn’t just replace it, you can’t take that interface and make it reentrant (you can almost make it «thread safe» with thread local storage, but it would still not be reentrant).

Even if you just took getenv away altogether, there is still the problem that you have the environ variable which would require some serious compiler level support to make thread safe, since it is just data.

Really, using environment variables for anything other than «setting it up before the process starts or at process start, and only reading from it from that point on» is going to probably end in tears if you have more than one thread. setenv and putenv don’t have a rich enough interface to express something like «set this set of environment variables atomically» and likewise getenv doesn’t have a way to express «read this set of environment variables atomically».

_dupenv_s is somewhat silly in my opinion, because if using that suddenly makes your code safe, it could probably done in a safe way with getenv. _dupenv_s solves a tiny subset of the problems with using environment variables in a multithreaded scenario.

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

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • C422 64 ошибка форд фокус
  • C422 64 ошибка форд транзит