sprintf错误“变量可能不安全”(C4996)...替代方法?

时间:2018-07-06 19:46:28

标签: c++ windows networking adapter bootp

这是我的代码:

#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#pragma comment(lib,"ws2_32.lib")
#include "stdafx.h"
#include <assert.h>
#include "Bootpd.h"
#include <iostream>
#include <string>
#include <iphlpapi.h>


char *MAC() {
    PIP_ADAPTER_INFO AdapterInfo;
    DWORD dwBufLen = sizeof(AdapterInfo);
    char *mac_addr = (char*)malloc(20);

    AdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
    assert(AdapterInfo != NULL); //Error allocating memory

    // Make an initial call to GetAdaptersInfo to get the necessary size into the dwBufLen variable
    if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == ERROR_BUFFER_OVERFLOW) {
        AdapterInfo = (IP_ADAPTER_INFO *)malloc(dwBufLen);
        assert(AdapterInfo != NULL);
    }

    if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == NO_ERROR) {
        PIP_ADAPTER_INFO info = AdapterInfo; //Copy information
        sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X",
            info->Address[0], info->Address[1],
            info->Address[2], info->Address[3],
            info->Address[4], info->Address[5]);
    }
    free(AdapterInfo);
    return mac_addr;
}

我正在Windows 10上使用VS2015。我正在尝试将网络适配器的MAC地址信息格式化为看起来像MAC地址(aa:bb:cc:dd:ee:ff)。我已经尝试在_CRT_SECURE_NO_WARNINGS语句上方定义4996并禁用警告#include,但没有成功。我有什么想念的吗?或者有人知道有其他方法可以解决sprintf错误variable may be unsafe吗?谢谢。

1 个答案:

答案 0 :(得分:1)

编译器抱怨可能会超出mac_addr数组。试一下sprintf_s。 https://en.cppreference.com/w/c/io/fprintf