Search code examples
c++strncpy

Why didn't work C++ code(strncpy_s)?


I'm C++ beginner.

When I have studied Class of C++, this example code did not work.

This code is interrupted by strncpy_s() func in NameCard class constructor.

I tried debugging, but I could not find the cause.

Could you help me? This is full source code

Have a nice day.

NameCard(char *name, char *phone, char *company, char *position)
{
    this->name = new char(strlen(name) + 1);
    this->phone = new char(strlen(phone) + 1);
    this->company = new char(strlen(company) + 1);
    this->position = new char(strlen(position) + 1);

    strncpy_s(this->name, strlen(name) + 1, name, strlen(name));
    strncpy_s(this->phone, strlen(phone) + 1, phone, strlen(phone));
    strncpy_s(this->company, strlen(company) + 1, company, strlen(company));
    strncpy_s(this->position, strlen(position) + 1, position, strlen(position));
}

Solution

  • You have misused the new operator.

    All lines like:

    new char(strlen(name) + 1);
    

    should be replaced by:

    new char[strlen(name) + 1];
    

    new char(X) allocates a buffer for one single char which will be filled with the character whose ASCII code is X.

    new char[X] allocates a buffer for X chars; this is what you want here.

    But best would be using std::string in first place.