resize 함수 작성 중 문제가 있어 질문드립니다.
302
작성한 질문수 2
resize함수 작성 중에
위와 같이 배열의 길이를 저장하는 length의 길이를 변경하는 코드를 넣으면 아래와 같은 런타임 에러가 발생합니다
힙 버퍼 종료 후에 메모리에 작성을 했다는데,
어떤 의미인지 이해가 되지 않아서 질문 드립니다.
전체 코드 :
class IntArray
{
private:
int m_length = 0;
int* m_ptr = nullptr;
public:
//Constructors
IntArray(const int &length)
:m_length(length)
{
m_ptr = new int[length];
}
IntArray(const std::initializer_list<int>& list)
: IntArray(list.size())
{
int count = 0;
for (auto& e : list)
{
m_ptr[count++] = e;
}
}
//Destructors
~IntArray()
{
delete[] m_ptr;
}
//reset
void reset()
{
delete[] m_ptr;
m_ptr = new int[m_length];
}
//resize
void resize(const int& x)
{
if (m_length == x)
return;
else if (m_length < x)
{
int* temp = new int[x];
for (int i = 0; i < m_length; i++)
{
temp[i] = m_ptr[i];
}
//m_length = x;
delete[] m_ptr;
m_ptr = temp;
}
else if (m_length > x)
{
int* temp = new int[x];
for (int i = 0; i < x; i++)
{
temp[i] = m_ptr[i];
}
//m_length = x;
delete[] m_ptr;
m_ptr = temp;
}
}
//insertBefore(const int & value , const int & ix);
void insertBefore(const int& value, const int& ix)
{
resize(m_length + 1);
for (int i = m_length; i > ix; i--)
{
m_ptr[i] = m_ptr[i - 1];
}
m_ptr[ix] = value;
}
//remove(const int & ix);
void remove(const int& ix)
{
for (int i = ix; i < m_length-1; i++)
{
m_ptr[ix] = m_ptr[ix + 1];
}
}
//push_back(const int& value);
void push_back(const int& value)
{
resize(m_length + 1);
m_ptr[m_length] = value;
}
friend std::ostream& operator << (std::ostream& out,const IntArray& intarr)
{
for (int i = 0; i <intarr.m_length ; i++)
{
out << intarr.m_ptr[i] << " ";
}
out << std::endl;
return out;
}
};
int main()
{
IntArray my_arr {1,3,5,7,9};
my_arr.insertBefore(10, 1); //1,10,3,5,7,9
//my_arr.remove(3); //1,10,3,7,9
//my_arr.push_back(13); //1,10,3,7,9,13
std::cout << my_arr << std::endl;
}
답변 1
0
안녕하세요 :)
해당 오류는 어딘가에서 메모리 관리(메모리 할당, 해제)를 잘못했을 때 곧잘 등장하는 오류입니다..
중단점을 찍어보면 m_length = x; 코드로 인한 문제는 소멸자에서 발생한다는 걸 알 수 있습니다.
(달리 말해, 소멸자 전까지는 문제가 발생하지 않는다는 것이지요.)
아래 insertBefore 함수의 코드를 보면 resize 함수를 호출한 뒤에 m_length만큼 m_ptr를 재조정하는 과정이 있습니다.
//insertBefore(const int & value , const int & ix);
void insertBefore(const int& value, const int& ix)
{
resize(m_length + 1);
for (int i = m_length; i > ix; i--)
{
m_ptr[i] = m_ptr[i - 1];
}
m_ptr[ix] = value;
}
그런데 resize함수에서 m_length 크기를 임의로 변경해버리면
당연히 이후 호출되는 아래 insertBefore 함수 코드에 영향이 갈 것이고,
for (int i = m_length; i > ix; i--)
{
m_ptr[i] = m_ptr[i - 1];
}
그 과정에서 m_ptr[i]의 값이 엉뚱하게 초기화됩니다.
그렇기에 소멸자의 delete[] m_ptr; 에서 문제가 발생한 것으로 보입니다.
즉, 제 생각에는
m_length = x; 코드가 m_ptr[i] = m_ptr[i-1] 에 끼치는 영향을 중심으로 생각해보시면
도움이 될 듯 합니다..
추가적인 질문이 있다면 언제든 댓글 달아주세요!
감사합니다 :)
변수가 메모리에 저장되는 것을 알려주는 강의가 어떤강의였죠
1
481
1
메모리 주소 10진수로 출력
1
672
1
클래스 템플릿 특수화에서 boolalpha로 표현된 리턴값에 대해 질문이 있습니다.
1
515
1
여러가지 리턴 타입에 관한 강의가 어떤 걸까요?
1
549
1
메모리 주소에 관한 질분
0
687
1
인터페이스 클래스에서 reportError의 매개변수에 대해 궁금한 것이 있습니다.
0
558
1
형변환 오버로딩에서 const 관련 질문이 있습니다.
0
448
1
Digit 뒤에 reference를 사용하는 이유
0
512
1
4.2 전역 변수, 정적 변수, 내부 연결, 외부 연결
0
325
1
dat파일이...
0
540
1
TODO:대입 연산자 오버로딩에 대한 소스코드입니다.
0
651
1
복사 생성자 관련 질문이 있습니다.
0
456
1
수업 중 궁금한점이 있습니다.
1
392
1
라이브러리자체가 이해가 되지 않습니다.
0
565
1
마지막 예제 질문
0
305
1
증감연산자 위치에 따른 수행 순서 질문입니다.
0
382
1
단항 연산자 오버로딩에서 return 부분에 질문이 있습니다.
1
416
1
friend함수 관련 질문이 있습니다.
0
313
1
operator+ 정의부분에서 궁금한 것이 있습니다.
0
448
1
3분 17초 질문
0
354
1
함수에 값을 대입한다는 개념이 이해가 되지 않습니다.
0
450
1
int getvalue() const에서 const는 왜 뒤에 붙는건가요?
0
453
2
const Something &st에서 const를 빼면 안되나요?
0
304
1
friend함수는 다른 클래스의 멤버함수로 쓸 수 없나요??
1
495
1





