这里的 strncpy_s() 有什么问题?

Sta*_*her 1 c++ strncpy

我正在阅读我的教科书并试图解决给读者的问题。

空闲代码是我的答案源文件中的函数定义。

我想将字符串的内容复制到另一个字符串。

我选择了函数 strncpy_s()。

但它不起作用。

Microsoft Visual Studio 说调试断言失败!

我不知道如何解决它。

牛.h

// 类声明

#include <iostream>
#ifndef COW_H_
#define COW_H_

class Cow {
char name[20];
char * hobby;
double weight;
public:
Cow();
Cow(const char * nm, const char * ho, double wt);
Cow(const Cow & c);
~Cow();
Cow & operator=(const Cow & c);
void ShowCow() const;  // display all cow data   
}; 
#endif
Run Code Online (Sandbox Code Playgroud)

牛.cpp

// 类方法

Cow::Cow(const char * nm, const char * ho, double wt)
{
    int len = std::strlen(nm);
    strncpy_s(name, len, nm, len);
    name[19] = '\0';

    len = std::strlen(ho);
    hobby = new char[len + 1];
    strncpy_s(hobby, len, ho, len);
    hobby[len] = '\0';

    weight = wt;
}

Cow::Cow()
{
    strncpy_s(name, 19, "no name", 19);
    name[19] = '\0';

    int len = std::strlen("no hobby");
    hobby = new char[len + 1];
    strncpy_s(hobby, len, "no hobby", len);
    hobby[len] = '\0';

    weight = 0.0;
}

Cow::Cow(const Cow & c)
{
    int len = std::strlen(c.name);
    strncpy_s(name, len, c.name, len);
    name[19] = '\0';

    len = std::strlen(c.hobby);
    hobby = new char[len + 1];
    strncpy_s(hobby, len, c.hobby, len);
    hobby[len] = '\0';

    weight = c.weight;
}

Cow::~Cow()
{
    delete [] hobby;
}

Cow & Cow::operator=(const Cow & c)
{
    if (this == &c)
        return * this;

    delete [] hobby;

    int len = std::strlen(c.name);
    strncpy_s(name, len, c.name, len);
    name[19] = '\0';

    len = std::strlen(c.hobby);
    hobby = new char[len + 1];
    strncpy_s(hobby, len, c.hobby, len);
    hobby[len] = '\0';

    weight = c.weight;
    return * this;
}

void Cow::ShowCow() const
{
    cout << name << ", " << hobby << ", " << weight << endl;  
}
Run Code Online (Sandbox Code Playgroud)

使用cow.cpp

  #include <iostream>
  #include "cow.h"


  int main()
  {
      Cow Japan;
      Japan.ShowCow();

      Cow America("Aspen", "Swim", 307.45);
      America.ShowCow();

      return 0;
  }
Run Code Online (Sandbox Code Playgroud)

Ari*_*nhh 5

strncpy_s 文档

这些函数尝试将 strSource 的前 D 个字符复制到 strDest,其中 D 是 count 和 strSource 长度中的较小者。如果这些 D 字符适合 strDest(其大小指定为 numberOfElements)并且仍然为空终止符留出空间,则复制这些字符并附加终止空值;否则,strDest[0] 设置为空字符并调用无效参数处理程序,如参数验证中所述。

让我们考虑您的代码:

int len = std::strlen("no hobby");
hobby = new char[len + 1];
strncpy_s(hobby, len, "no hobby", len);
Run Code Online (Sandbox Code Playgroud)

的第二个参数strcpy_s是以字符为单位的缓冲区大小。第四 - 复制的字符数。由于您正在传递相同的len变量,因此strcpy_s检测到该缓冲区的大小不足(因为尾随 \0 应该有一个空间)并调用无效参数处理程序。这正常工作:

int len = std::strlen("no hobby");
hobby = new char[len + 1];
strncpy_s(hobby, len+1, "no hobby", len);
Run Code Online (Sandbox Code Playgroud)

检查您使用的其他地方是否有strncpy_s此错误。此外,在调试断言窗口中实际阅读文本也是一个好主意。在这种情况下,错误源非常简单:

调试断言失败