디버깅 했을때 액세스 위반이라고 오류가 납니다.
조회수 647회
컴파일은 잘 되는데, 디버깅할때 액세스 위반이 뜨네요. 제가 뭘 잘 못 한 걸까요? 포인터를 잘 못 줬나요?
#include <iostream>
#include <string>
using namespace std;
class Complex {
private:
float real, imaginary;
public:
Complex(float _real, float _imaginary) : real(_real), imaginary(_imaginary) {};
auto operator==(Complex rhs) {
return (real == rhs.real) && (imaginary == rhs.imaginary);
}
};
class MyString {
private:
const char *str;
public:
MyString():str(""){}
MyString( const char *_str) : str(_str) {}
auto operator==(MyString rhs) {
return (!strcmp(str, rhs.str));
}
};
template <class T, int size>
class List {
T *elem;
int size;
int currentSize;
public:
List() : currentSize(0) {}
List(int _size) : size(_size), currentSize(0) { elem = new T[_size]; }
List(const List& another) : size(another.size), currentSize(another.currentSize) {
elem = new T[size];
for (int i = 0; i < currentSize; i++) {
elem[i] = another.elem[i];
}
}
int add(const T &anElem) {
elem[currentSize] = anElem;
return currentSize++;
}
void find(const T &anElem) const {
for (int i = 0; i < currentSize; i++) {
cout << typeid(elem[i]).name() << endl;
if (elem[i] ==anElem) {
cout << "exist" << endl;
}
else {
cout << "not exist" << endl;
}
}
}
void remove(const T &anElem) const {
for (int i = 0; i < currentSize; i++) {
if (typeid(elem[i]) == typeid(anElem)) {
for (int j = i; j < (currentSize - 1); j++) {
elem[j] = elem[j + 1];
}
}
else {
cout << "not exist" << endl;
}
}
}
void remove(const int location) const {
for (int j = location; j < (currentSize - 1); j++) {
elem[j] = elem[j + 1];
}
}
List operator = (const List& L){
for (int i = 0; i < currentSize; i++) {
L.elem[i] = elem[i];
}
return L;
}
~List() { delete [] elem; }
};
int main() {
List<Complex, 100> cList;
List<MyString, 200> sList;
int i1 = cList.add(Complex(0, 0));
cList.add(Complex(1, 1));
int i2 = sList.add("abc");
sList.add("def");
cList.find(Complex(1, 0));
sList.find("def");
cList.remove(i1);
sList.remove("abc");
List<MyString, 200> s2List(sList);
List<MyString, 200> s3List;
s3List.add("123");
s3List = s2List;
s3List.remove("def");
}
1 답변
-
디버거로 돌려 봤어요.
int i1 = cList.add(Complex(0, 0));
여기서 타고 들어가서, 아래 add 메소드에서
int add(const T &anElem) { // elem = 0xCCCCCCCC, currentSize = 0 elem[currentSize] = anElem; // <<< access violation return currentSize++; }
접근 예외가 발생합니다.
cList
가List()
생성자로 생성되면서,elem
에 메모리 할당이 되지 않았습니다. (디버거로 break point 걸고 확인해 보세요.)
댓글 입력