c++ - 我是否错误地实现了 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);
}
解决方案
值得一提的是,除了参数 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
推荐阅读
- excel - 将 Excel 中的单元格数据输入 Outlook
- postgresql - Postgres 函数触发序列依赖错误
- javascript - React JS - data.map 无法使用数据创建列表
- unit-testing - 在单元测试中实现 IDisposable 没有意义吗?
- c++ - Return Value Optimization: Explicit move or implicit?
- java - 如何将 JLabel 定位在北方但不完全位于顶部?
- javascript - 如何更改 discord.js 中角色的权限?
- ruby-on-rails-5 - 如何选择模型字段来表示活动管理仪表板上的多对一关系?
- c# - C# Blazor:如何使用 e.preventDefault() 防止在 JS 中输入特定键?
- javascript - 我原以为我只会得到一行结果,但我得到了三行结果