c++ - strcpy() 在 Visual Studio 2012 中的行为

标签 c++ visual-studio-2012

作为老师布置的任务,我们被告知要编写一个简单的类。在我编写的构造函数中(C++ Visual Studio 2012):

void CCar::CCar(char* model){
    if(this->model!=NULL) delete[] this->model;
    this->model= new char[strlen(model)+1];
    strcpy(this->model, model);
}

我被告知我的代码是错误的,因为我使用 new 动态分配了内存,我不应该因为strcpy分配内存,所以我写的是一个坏习惯的例子。包括<string.h>没有进一步#define就像我被告知的那样指定安全功能,你能给我指一个引用吗 strcpy的行为被彻底指定了吗?我的代码正确吗?

最佳答案

strcpy 不分配任何内存。

在C标准中,函数是这样描述的

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined. Returns 3 The strcpy function returns the value of s1.

其中 s1 和 s2 是函数参数。

构造函数看起来像

#include <cstring>

//...

CCar::CCar( const char* model )
{
    this->model = new char[std::strlen( model )+1];
    std::strcpy( this->model, model );
}

或者您可以使用标准类 std::string。即数据成员模型必须被定义为具有 std::string

类型

在这种情况下,构造函数看起来像

#include <string>

//...

CCar::CCar( const char* model ) : model( model )
{
}

顺便说一句,你的构造函数中的这条语句是错误的

if(this->model!=NULL) delete[] this->model;

它可能导致未定义的行为,因为对于没有静态存储持续时间的类的本地对象,数据成员模型可以具有任意值。因此,尽管模型可能不等于 NULL,但仍尝试删除未分配的内存。

关于c++ - strcpy() 在 Visual Studio 2012 中的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25613744/

相关文章:

c++ - Windows C++ 整数数组堆损坏

c++ - move : what does it take?

c# - 如何访问 IKVM 移植的 Java 库的 .net 资源

c++ - 类似于嵌套互斥体但更通用的东西?

c++ - 我需要一些帮助来理解 Nicolai Josuttis 书中的这一段

C++ 方法覆盖

c++ - vector 对

asp.net - VS 2010 : Value of type 'System.Web.UI.HtmlControls.HtmlGenericControl' cannot be converted to 'System.Web.UI.HtmlControls.HtmlTableRow'

c++ - 链接到 DLL 文件中的 Boost

c# - 在 C# 中调用 C++ 库