首页 > 解决方案 > 我是否错误地实现了 strcpy_s?

问题描述

我从 C++ 编译器收到此错误消息:

'strcpy_s' 未在此范围内声明

我浏览了许多博客,阅读了文档,试图纠正这个问题。这是一个安全编码的任务,虽然我不是程序员。

这是我的代码:

#include <iostream>
#include <string.h>
using namespace std;
    
void sampleFunc(char inStr[])
{
    char buf[10];
    buf[9] ='\0';
    strcpy_s(buf, inStr);
    cout << "\n" << buf << "\n";
    return;
}

int main(){
    char inStr[10];
    cout << "Enter String: ";
    cin >> inStr;
    sampleFunc(inStr);
}

标签: c++

解决方案


值得一提的是,除了参数 count to strcpy_s,参考手册

strcpy_s仅当STDC_LIB_EXT1由实现定义并且用户 在包含 string.h 之前将STDC_WANT_LIB_EXT1定义为整数常量 1时才保证可用。

因此,正确的用法是上面参考链接中提到的

#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>

// and somewhere the the code

#ifdef __STDC_LIB_EXT1__
    set_constraint_handler_s(ignore_handler_s);
    int r = strcpy_s(dst, sizeof dst, src);
    printf("dst = \"%s\", r = %d\n", dst, r);
    r = strcpy_s(dst, sizeof dst, "Take even more tests.");
    printf("dst = \"%s\", r = %d\n", dst, r);
#endif

推荐阅读