2016-11-06 46 views
-1

当我尝试删除动态分配数组时,我的程序一直崩溃。当我调试程序这个错误出现:删除动态数组时发生崩溃

#0 0x47a949 std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)() (??:??) 
#1 0x48a940 std::cerr() (??:??) 
#2 0x722924 ??() (??:??) 
#3 0x4010fd __mingw_CRTStartup() (??:??) 
#4 0x7729cf34 strerror_s() (C:\WINDOWS\SysWoW64\msvcrt.dll:??) 
#5 0x775d0719 ??() (??:??) 
#6 0x775d06e4 ??() (??:??) 
#7 ?? ??() (??:??) 

这是我的代码:

#include <iostream> 
#include <string> 
#include <stdlib.h> 

using namespace std; 

int main() 
{ 
    int numNames; 
    cout << "How many names do you want to enter?" << endl; 
    cin >> numNames; 
    std::string *names = new (nothrow) std::string[numNames]; 
    if (!names) 
    { 
     std::cout << "Could not allocate memory"; 
     exit(EXIT_FAILURE); 
    } 

    for (int i = 0; i <= numNames-1; i++) 
    { 
     cout << "Enter name #" << i+1 << endl; 
     cin >> names[i]; 
    } 

    for (int start = 0; start < numNames; start++) 
    { 
     int smallestName = start; 
     for (int currentName = start + 1; currentName < numNames; currentName++) 
     { 
      if (names[currentName] < names[smallestName]) 
      { 
       smallestName = currentName; 
      } 
     } 

     swap(names[start], names[smallestName]); 
    } 

    cout << endl << "Here is your sorted list: " << endl; 
    for (int i = 0; i <= numNames; i++) 
    { 
     cout << names[i] << endl; 
    } 

    delete[] names; 
     names = nullptr; 

    return 0; 
} 

我试图与这两个名字= 0;和names = nulltptr;他们都没有工作。 我希望你能帮我找到我的问题。 干杯!

+3

解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –

+2

在你最后一个for循环中...我<= numNames ..应该是..我 HazemGomaa

+1

当我尝试它时,工作正常,什么值会使它崩溃 –

回答

1

您的错误不是因为删除语句。这是因为当你在循环for (int i = 0; i <= numNames; i++)中输出时,由于<=,你正在访问一个在内存中不可用的元素,因此程序崩溃了。要解决此问题,只需使用i < numNames

+0

非常感谢您的帮助! – Elhoej