인프런 커뮤니티 질문&답변
resize 함수 작성 중 문제가 있어 질문드립니다.
작성
·
294
0
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] 에 끼치는 영향을 중심으로 생각해보시면
도움이 될 듯 합니다..
추가적인 질문이 있다면 언제든 댓글 달아주세요!
감사합니다 :)






답변 감사합니다!
생각보다 단순한 실수 였네요..
답변해주신거 참고해서 코드 완성했습니다!