c++ 왕초보 오버플로 질문드립니다

조회수 418회
#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;
}

위의 코드를 실행하면 디버그와 경고 2개가 나옵니다.

그런데 이상하게도 실행은 잘만 됩니다.. 경고를 구글링해도 잘 모르겠어서 질문드립니다. 디버그를 없앨려면 어떤 부분의 코드를 수정해야 할까요?

이미지

이미지

이미지

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    지금 sizeof() 연산자의 용도를 제대로 모르고 있는 상태로 코드를 작성하고 있는 것 같습니다.

    질문의 코드에서 생성자 함수를 아래와 같이 수정해야 합니다.

    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;
    }
    
    • 결과

    이미지

    • (•́ ✖ •̀)
      알 수 없는 사용자
    • 아 그렇네요. 제가 sizeof()를 잘 몰랐네요.. 감사합니다 koladuckhu 2021.12.17 21:22

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)