2013-03-12 4 views
0

У меня есть список упорядоченных массивов. И в моей функции изменения размера я создаю новый массив и присваиваю ему значения старого массива, а затем удаляю старый массив, используя delete[] arrayname;. Это приводит к ошибке во время выполнения, когда функция изменения размера входит в игру. Вызывается dbgheap.c. Кто-нибудь видел это раньше?Удаление массива приводит к ошибке во время выполнения. C++

Вот мой код:

//-------------------------------------------------------------------------------------------- 
// Name:   OrderedArray.h. 
// Description: Header file for the use in OrderedArray.cpp. 
//-------------------------------------------------------------------------------------------- 
#ifndef ORDEREDARRAY_H 
#define ORDEREDARRAY_H 
#include <iostream> 

using namespace std; 
//-------------------------------------------------------------------------------------------- 
// Name:   template <class Datatype> 
// Description:   
//-------------------------------------------------------------------------------------------- 
template <class Datatype> 
//-------------------------------------------------------------------------------------------- 
// Class: OrderedArray.    
//-------------------------------------------------------------------------------------------- 
class OrderedArray 
{ 
//-------------------------------------------------------------------------------------------- 
// Member Variables.   
//-------------------------------------------------------------------------------------------- 
private: 
Datatype* m_array; 
int size; 
int g_size; 
int num_elements; //Counter for the number of elements in the Array. 

void Resize(int p_size)//resizes the array to the size of p_size 
    { 
     cout << "Did i get this far "; 
     if(p_size < 0)//checks if new size is less than 0 
     { 
      cout << "ERROR! Size of an array can not be less than 0!" << endl; 
     } 
     else//else its ok to continue 
     { 
      Datatype* newArray = new Datatype[p_size];//creates a pointer newArray that points at a new array 
      if(newArray == 0) 
      { 
       return; 
      } 
      cout << "Did i get this far "; 
      int min; 

      if(p_size < size)//checks the if the new array is smaller than the old one 
       min = p_size; 
      else//else its going to be bigger 
       min = size; 
      cout << "Did i get this far "; 
      int index; 
      int temp = num_elements;//puts num_elements into a temporary variable called temp 
      num_elements = 0;//num_elements is set to 0 
      for(index = 0; index < min; index++) 
      { 
       newArray[index] = m_array[index];//places everything from the old array into the new array that will fit. 
       if(num_elements < temp)//if the num_elements is less than temp(the original num_elements) 
       { 
        num_elements++;//increment num_elements. This will keep incrementing to create the new num_elements based the number of elements cut off in the resize 
       } 
      } 
      size = p_size;//sets the old size to be equal to the new size 
      cout << "Did i get this far "; 
      if(m_array != 0) 
      { 
      cout << "\nI am just about to delete "; 
      delete[] m_array;//deletes the old array 
      } 
      m_array = newArray;//makes m_array point at the new array 
      newArray = 0;//makes newArray a null pointer 
     } 
    } 
//--------------------------------------------------------------------------------------- 
// Name:    Push 
// Description:  
//--------------------------------------------------------------------------------------- 
void push(Datatype p_item) 
{ 
    if(num_elements == size)//checks if the array is full and needs to be resized 
    { 
     Resize(size + g_size);//calls the resize function 
    } 

    int pos = num_elements; 
    for(int x=0;x<num_elements;x++) 
    { 
     if(p_item < m_array[x]) 
     { 
     pos=x; 
     } 
    } 

    //loops through the array from high to low moving all values to the right 
    //to make space for the passed in value until it gets to the right place 
    for(int index = num_elements; index >= pos; index--) 
    { 
     m_array[index] = m_array[index-1];//moves the values to the right 
    } 
     m_array[pos] = p_item;//the passed in value is positioned into its ordered position 
     num_elements++; 

    cout<< "Num Elements " << num_elements; 
    cout<< "Size " <<size; 
} 

    //-------------------------------------------------------------------------------------------- 
    // Name:   Constructor. 
    // Description: Constructs the Array. 
    //-------------------------------------------------------------------------------------------- 
    OrderedArray(int p_size, int grow_size) 
    { 
     //Sets the Array size. 
     m_array = new Datatype[p_size,grow_size]; 
     size = p_size; 
     g_size = grow_size; 
     //How many elements are in the Array. 
    num_elements = 0;    
} 

// размер и g_size приведены его значение пользователем при запуске программы.

+0

Вы вероятно перезапись границы вашего массива, а проверка не выполняется, пока освобождения памяти в куче. Вы должны показать, как вы заполняете массив, и попытайтесь уменьшить это до http://sscce.org/ – Chad

+0

. Хорошо, я заселяю массив упорядоченным нажатием на усмотрение пользователя ... Il редактирует функцию push в мой код :) – Becca

+0

И при отладке ошибок во время выполнения - используйте отладчик (например, gdb). Это просто делает все намного проще. – sonicwave

ответ

1

Вашего код m_array = new Datatype[p_size,grow_size]; в конструкторе должен принимать только один параметр, который является размером массива.

Изменить это: m_array = new Datatype[p_size];

+1

Не злиться, но почему это стало принятым ответом, когда он был опубликован после того, как я решил, что это проблема, и мой ответ был принят? – paddy

+0

Потому что у вас есть еще больше репутации, чем Pendo. лол. Как и я, ОП, вероятно, сначала читает короткий ответ. Итак, я предполагаю, что он видел обе записи в то же время и решил сначала прочитать короткий ответ. – ArgumentNullException

4

Там может быть какой-то другой вопрос здесь, но самая очевидная вещь, которую я могу видеть это:

for(int index = num_elements; index >= pos; index--) 
{ 
    m_array[index] = m_array[index-1]; 
} 

Если pos бывает равным нулю, то в конечном итоге сделать это:

m_array[0] = m_array[-1]; 

Эта проблема показывается немедленно (когда num_elements равно нулю - вы не указали свой конструктор, но я надеюсь, что вы все инициализировали).

Изменение >= до > в петле может решить все ваши проблемы.

Концептуально, вы должны согласиться с этой логикой. Нет смысла перемещать товар доm_array[pos] вперед до m_array[pos], когда вы собираетесь заменить его на новый предмет.


[править] Теперь, когда вы разместили свой конструктор:

m_array = new Datatype[p_size,grow_size]; 

Это будет инициализировать ваш массив с размером grow_size вместо p_size, так как работает оператор запятая. Прочитайте это: How does the Comma Operator work

Пожалуйста, сделайте это вместо:

m_array = new Datatype[p_size]; 
+0

Кроме того, не 'm_array [index]' один за концом при первом прохождении через цикл? –

+0

Я сделал это ... к несчастью, никакой радости ... Да, в конструкторе все истистиализировано. Я отредактирую его в ... – Becca

+0

@JesseGood Нет, посмотрите на верхнюю часть функции «push». Массив должен быть изменен. – paddy

Смежные вопросы