Ошибка при использовании динамических массивов в моем основном классе

0

Я новичок в программировании C++ и пытается изучить динамический массив. У меня есть код из моей книги для вызова List, и я пытаюсь использовать функции в своем основном классе. Получил ошибку ниже при этом...

Ошибка отладки: "CRT обнаружил, что приложение записано в память после завершения буфера кучи

test_List.h

#include "stdafx.h"
#include "List.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
List d;
List *arr = &d;
size_t user_input;
//arr1 = new List(5);
cout << "Enter the value in to your array: ";
cin >> user_input;
arr->append(user_input);

return 0;
}
// List.cpp : Defines the entry point for the console application.
// List.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"
#include "List.h"
#include <iostream>
using namespace std;
List::List(size_t capacity)
{
data_ = new int[capacity_];
capacity_ = capacity;
size_ = 0;
}

List::List(const List &list)
{
copy(list);
}

List::~List()
{
cout << "delete ";
delete[] data_;
}

void List::copy(const List &list)
{
size_t i;
size_ = list.size_;
capacity_ = list.capacity_;
data_ = new int[list.capacity_];
for (i = 0; i < list.capacity_; ++i)
    {
    data_[i] = list.data_[i];
    }
}

List& List::operator=(const List &list)
{
if (&list != this)
{
    //deallocate existing dynamic array
    delete[] data_;
    //copy the data
    copy(list);
}
return *this;
}

List& List::operator+=(const List &list)
{
size_t i;
size_t pos = size_;
if ((size_ + list.size_) > capacity_)
{
    resize(size_ + list.size_);
}
for (i = 0; i < list.size_; i++)
{
    data_[pos++] = list.data_[i];
}
size_ += list.size_;
return *this;
}

void List::append(int item)
{
if (size_ == capacity_)
{
    resize(2 * capacity_);
}
data_[size_++] = item;
}



//should this method have a precondition
void List::resize(size_t new_size)
{
int * temp;
size_t i;

capacity_ = new_size;
temp = new int[capacity_];
for (i = 0; i <= size_; ++i)
{
    temp[i] = data_[i];
}
delete[] data_;
data_ = temp;
}



#ifndef _LIST_H_
#define _LIST_H__

#include "stdafx.h"
#include <cstdlib>

class List
{
public:
List(size_t capacity = 10); // constructor - allocates dynamic array
List(const List &a); // copy constructor
~List(); // destructor

int& operator[] (size_t pos); // bracket operator
List& operator=(const List &a); //assignment operator
List& operator+=(const List &a); // += operator
void append(int item);
size_t size() const { return size_; }
private:
void copy(const List &a); 
void resize(size_t new_size); // allocate new larger array
int *data_; // dynamic array
size_t size_; // size of dynamic array
size_t capacity_; // capacity of dynamic array 
};

inline int& List::operator [] (size_t pos)
{
return data_[pos];
}

#endif _LIST_H_

Может ли кто-нибудь помочь мне понять и решить эту проблему....

Теги:
dynamic-arrays

2 ответа

1

Вы пропустили инициализацию capacity_:

List::List(size_t capacity) :
    size_(0), data_(new int[capacity]), capacity_(capacity)
{

}

Обратите внимание, что вы должны использовать список инициализации для инициализации элементов в конструкторе.

1
List::List(size_t capacity)
{
    data_ = new int[capacity_];

Здесь вы не инициализировали capacity_ перед использованием его как размер массива. Перейдите в

data_ = new int[capacity];

или назначить capacity_ перед распределением для data_.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню