C++ I'd like to ask you a question

Asked 2 years ago, Updated 2 years ago, 29 views

#include <iostream>
#include <string.h>
using namespace std;

class String {
private:
    char* strData;
    int len;
 public:
     String() : strData(NULL), len(0) {}
     String(const char* str) {
         len = strnlen_s(str, sizeof(str)); 
         strData = new char[len + 1];   
         strncpy_s(strData, sizeof(strData),str,sizeof(str)); 
      }
     ~String() {
         if (strData != NULL) { delete[] strData; }
      }
     const char *GetStrData() const {
         if (strData != NULL) return strData;
         return "";
     }
     int GetLen() const {
         return len;
     }
};

int main() {
    String s1;
    String s2("Hello");
    cout << s1.GetLen() << endl;
    cout << s1.GetStrData() << endl;
    cout << s2.GetLen() << endl;
    cout << s2.GetStrData() << endl;
}

Running the above code will result in a debug and 2 warnings.

But strangely enough, it works. I'm asking because I don't understand even if I google the warning. What part of code should I modify to eliminate debugs?

c++

2022-09-20 11:40

1 Answers

It seems that you are writing the code without knowing the purpose of the sizeof() operator properly.

In the code of the question, the constructor function should be modified as follows.

String(const char* str)
{
        len = strlen(str);
        strData = new char[len + 1];
        strncpy_s(strData, len + 1, str, len + 1);
}
#include <iostream>
#include <string.h>
using namespace std;

class String {
private:
    char* strData;
    int len;
public:
    String() : strData(NULL), len(0) {}
    String(const char* str) {
        len = strlen(str);
        strData = new char[len + 1];
        strncpy_s(strData, len + 1, str, len + 1);
    }
    ~String() {
        if (strData != NULL) { delete[] strData; }
    }
    const char* GetStrData() const {
        if (strData != NULL) return strData;
        return "";
    }
    int GetLen() const {
        return len;
    }
};

int main()
{
    String s1;
    String s2("Hello");
    cout << s1.GetLen() << endl;
    cout << s1.GetStrData() << endl;
    cout << s2.GetLen() << endl;
    cout << s2.GetStrData() << endl;
}


2022-09-20 11:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.