프로그래밍

 3198, 1/160 회원가입  로그인  
   호박
   C++ 함수 관련 질문드립니다~

http://www.hackerschool.org/HS_Boards/zboard.php?AllArticle=true&no=6479 [복사]


#include <iostream>
using namespace std;

class MyString {
private:
        char *pbuf;

public:
        MyString(const char *s = NULL);
        MyString(MyString& s);
        ~MyString();

        void print();
        int getSize();
        MyString operator+(MyString& s);
};

MyString::MyString(const char *s) {
        if (s == NULL)
        {
                pbuf = new char[1];
                pbuf[0] = NULL;
        }
        else
        {
                pbuf = new char[::strlen(s) + 1];
                strcpy_s(pbuf, strlen(s) + 1, s);
        }
}

MyString::MyString(MyString &s)
{
        pbuf = new char[s.getSize() + 1];
        strcpy_s(pbuf, s.getSize() + 1, s.pbuf);
}

MyString::~MyString()
{
        if (pbuf)
                delete[] pbuf;
}

void MyString::print()
{
        cout << pbuf << endl;
}

int MyString::getSize()
{
        return strlen(pbuf);
}


MyString MyString::operator+(MyString& s) { // 오류가 나는 함수
        char *temp = new char[getSize() + s.getSize() + 1];
        strcpy_s(temp, getSize(), pbuf);
        strcat_s(temp,s.getSize() + 1, s.pbuf);
        MyString r(temp);
        delete[] temp;
        return r;
}

int main() {
        MyString s1("Hello ");
        MyString s2("World!");
        s2.print(); // 여기까진 정상 실행됨.
        MyString s3 = s1 + s2;
        s1.print();
        s2.print();
        s3.print();

        return 0;
}

------------------------------------------


위에가 코드 내용입니다. 위 코드를 실행하면

컴파일 시엔 에러가 나지 않는데 실행시

버퍼 공간이 모자라다면서 에러가 뜨더군요. 이 코드 원본은

3년전 출판된 책의 코드를 그대로 옮겨적은 건데요, 문제점이 다름 아닌

컴파일러를 비쥬얼 스튜디오 2013으로 바꾸면서 strcpy를 경고가 아니라

에러가 나게 바뀜으로써 strcpy_s로 임의로 수정해서 쓸 수 밖에 없더라구요.
그래서 원문에서 strcpy를 strcpy_s, strcat도 strcat_s로 수정했습니다.

그랬더니 이렇게 예상못한 오류가 나네요. 어떻게 해야 오류가 해결될까요?

  Hit : 4784     Date : 2014/07/28 07:36