在 C 中连接字符串的最安全的方法

问题描述 投票:0回答:1

strcat 极其不安全 strcpy 也极其不安全。 sprintf 几乎是不安全的。

我没有 sprintf_s、strcpy_s 或任何 _s 函数可用。

请说出 GCC 或 Clang 附带的所有基本可用库中哪些更好。 或者创建任何自定义函数来执行此操作。 我不需要“更安全”的东西,我需要“最安全”的东西。 其他帖子仅提到 _s 函数和 strncat “更安全”,这并不能回答我的问题。

连接字符串类型:const char*,函数必须以 const char* 格式返回答案。

以各种可能的方式尝试了所有 strcpy、strcat、sprintf 函数,但没有得到任何结果。

请按以下格式回答:

const char* func(const char* s1,const char* s2){
    //process concated_const_str=s1+s2
    return concated_const_str;
}
c string gcc string-concatenation memory-safety
1个回答
0
投票

这是一个非常简单的功能。

  1. 获取
    s1
    的长度。
  2. 获取
    s2
    的长度。
  3. 分配足够的空间来存储连接的字符串。不要忘记 NUL。
  4. 使用
    memcpy
    s1
    复制到缓冲区中。
  5. 使用
    memcpy
    s2
    复制到缓冲区中。
  6. 添加结尾的 NUL。
  7. 返回缓冲区。

返回类型为

const char *
而不是
char *
没有多大意义。

© www.soinside.com 2019 - 2024. All rights reserved.