C++程序在非预期情况下挂起以供输入
C++ program hangs for input when non intended
我正在编写一个简单的学校程序,演示选择排序使用rand()函数,但在输入数组的长度后,程序将挂起等待输入。当我输入一些无意义的(字符或字符串)时,程序会用零数组执行。
这是代码:
/*Selection sort implementation-
Autor: Adam Rychter
09/12/13*/
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int* selection_sort(int array[], int length);
int main(void) {
int length, num;
int* array;
cout << "Enter the length of array to sort: ";
cin >> length;
array = new int[length];
for(int i = 0; i < length; i++) {
num = rand();
array[i] = num;
}
int *sorted_array_ptr = selection_sort(array, length);
system("clear");
cout << "Sorted array:" <<endl;
for(int i = 0; i < length; i++) {
cout << " " << sorted_array_ptr[i];
}
free((void*) array);
cout << "n";
}
int* selection_sort(int array[], int length) {
for(int i = 0; i < length; i++) {
int max_index = i;
for(int j = i + 1; j < length; j++) {
if(array[j] > array[max_index]) {
max_index = j;
}
}
int tmp = array[i];
array[i] = array[max_index];
array[max_index] = tmp;
}
return array;
}
我使用的是启用了-o3优化的G++编译器。非常感谢您的回答。Adam Rychter
首先,删除这行
system("clear");
第二,改变这个,
free((void*) array);
至,
delete []array;
如果使用new
,则将通过delete
取消分配空间。如果使用malloc
,则将通过free
取消分配空间。两者混淆会造成问题。
与malloc/free
相比,更喜欢使用new/delete
。
根据C++FAQ Lite,
[16.4]为什么我应该使用new而不是值得信赖的旧malloc()?
常见问题解答:新建/删除调用构造函数/析构函数;new是类型安全的,malloc不是;new可以被类重写。
FQA:常见问题解答中提到的新事物的优点不是优点,因为构造函数、析构函数和运算符重载都是垃圾(请参阅当你没有垃圾收集时会发生什么?),以及类型这里的安全问题真的很小(通常你必须填补空白*malloc返回到右指针类型,以将其分配给类型化的指针变量,这可能很烦人,但远非"不安全")。
哦,使用值得信赖的旧malloc可以使用同样值得信赖&旧的realloc。可惜我们没有闪亮的新操作员更新或其他什么。
尽管如此,新事物还不足以证明偏离常规在整个语言中使用的样式,即使该语言是C++。在里面特别是,具有非平凡构造函数的类在如果您只是对对象进行malloc操作,则会造成致命的后果。为什么不使用新的贯穿整个代码?人们很少超载操作员,所以可能不会太妨碍你。如果他们真的超载了新的,你可以随时要求他们停下来。
相关文章:
- 挂起和取消挂起一个文件DLL
- 如何防止C++遗留代码中的挂起指针
- 为什么所有C++编译器都会崩溃或挂起此代码
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 构建挂起,即使是适度的文件大小
- 循环挂起迭代的 std::擦除 on std::list
- Poco::Net::FTPClientSession 在 open() 方法上挂起 129 秒,如果 ftp 主机不存
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 从不同进程中的另一个线程挂起/恢复线程或进程
- Boost (Beast) websocket:同步写入挂起
- 为什么析构函数挂起
- 使用互斥会挂起程序
- C++ 在 CIN 双精度时挂起,但如果输入整数,则继续
- C++程序在非预期情况下挂起以供输入
- 运行需要输入而不挂起的命令,但仍允许输入
- 字符串输入超过1000个字符时执行挂起
- 输入缓冲区中的挂起字符
- Std::cin有时挂起,有时在无效输入后永远重复
- 程序在控制台中挂起,而在c++中给出大的输入大小
- C++哈希表程序在输入值后挂起