동적 할당 배열을 삭제하려고하면 프로그램이 계속 충돌합니다. 내가 프로그램을 디버깅 할 때이 오류가납니다 :동적 배열을 삭제할 때 충돌이 발생합니다.
#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 시도; 및 이름 = nulltptr; 둘 중 누구도 일하지 않았습니다. 내 문제를 찾을 수 있도록 도와주세요. 건배!
이러한 문제를 해결하는 올바른 도구는 디버거입니다. 스택 오버플로를 묻기 전에 코드를 단계별로 실행해야합니다. 자세한 도움말은 [작은 프로그램 디버깅 방법 (Eric Lippert 작성)] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)을 참조하십시오. 문제를 재현하는 [최소, 완료 및 확인 가능] (http://stackoverflow.com/help/mcve) 예제와 함께 해당 질문을 \ [편집]해야합니다. 디버거. –
마지막으로 for ... ...
HazemGomaa
시도 할 때 잘 작동합니다. 어떤 값의 충돌이 발생합니까? –