C++程序在非预期情况下挂起以供输入

C++ program hangs for input when non intended

本文关键字:挂起 输入 情况下 程序 C++      更新时间:2023-10-16

我正在编写一个简单的学校程序,演示选择排序使用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操作,则会造成致命的后果。为什么不使用新的贯穿整个代码?人们很少超载操作员,所以可能不会太妨碍你。如果他们真的超载了新的,你可以随时要求他们停下来。