删除动态数组时崩溃

时间:2016-11-06 16:37:57

标签: c++ arrays dynamic delete-operator

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

 #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;他们都没有工作。 我希望你能帮我找到问题所在。 干杯!

1 个答案:

答案 0 :(得分:1)

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