【问题标题】:Keep Getting a Segmentation Fault On This?不断收到分段错误?
【发布时间】:2017-07-08 04:20:37
【问题描述】:

我不断收到以下代码的分段错误(核心转储)。关于为什么会发生这种情况的任何想法。该代码旨在从文本文档中读取数字,将它们转换为整数,执行基数排序并打印出数组。

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>

using namespace std;

int getMax(int arr[], int n)
{
    int max = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

void countSort(int arr[], int n, int exp)
{
    int output[n];
    int i, count[10] = {0};
    for (i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i >= 0; i--)
    {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixsort(int arr[], int n)
{
    clock_t clockStart;
    clockStart = clock();

    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countSort(arr, n, exp);

    cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
}

int StrToInt(string sti) 
{
    int f;
    stringstream ss(sti); //turn the string into a stream
    ss >> f;
    return f;
}

int main()
{
    int arr[10000];
    int i = 0;
    int result;
    string line = "";

    ifstream myfile;
    myfile.open("integers2.txt");
    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            getline(myfile, line);
            result = StrToInt(line);
            arr[i] = result;
            //cout<< arr[i] <<"\n";
            i++;
        }
    }


    int n = sizeof(arr)/sizeof(arr[0]);
    radixsort(arr, n);

    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << "\n";
    }

    return 0;
}

我用于输入的文本文件的内容: 1244 3455 6565 55 765 8768 687 879

【问题讨论】:

  • 您是否尝试过在调试器中运行它来确定代码中发生段错误的位置?
  • 不,我是 C++ 新手,刚刚学习
  • 文件的内容是列表中的数字,例如:1024 3456 4758 6879
  • while(!myfile.eof()) 是个坏主意。
  • 这不会崩溃,但我必须进行一些更改,因为我选择的编译器不支持可变大小的数组。不知道你的问题出在哪里。 ideone.com/520c9A 这更像是您的代码没有读取文件,它也不会崩溃。 ideone.com/9vN0Sq您真的是要对所有 10k 元素进行排序吗?

标签: c++ compiler-errors segmentation-fault radix-sort


【解决方案1】:

您的程序具有未定义的行为,因为它使用的数组条目比您使用数据初始化的要多。您将整个数组的长度传递给 n,即使其中只有一小部分(从 0i)已初始化。

更改代码以在读取循环中使用n 代替i,并将未修改的n 传递给排序函数。这将解决问题 (demo)。

int n = 0;
myfile.open("integers2.txt");
if(myfile.is_open()) {
    while (myfile >> arr[n]) {
        n++;
    }
}
radixsort(arr, n);

【讨论】:

    【解决方案2】:

    这是你的工作代码:

    #include <cstdlib>
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <string>
    #include <time.h>
    #include <sstream>
    
    using namespace std;
    
    int getMax(int arr[], int n)
    {
        int max = arr[0];
        for (int i = 1; i < n; i++)
            if (arr[i] > max)
                max = arr[i];
        return max;
    }
    
    void countSort(int arr[], int n, int exp)
    {
        int output[n];
        int i, count[10] = {0};
        for (i = 0; i < n; i++)
            count[(arr[i] / exp) % 10]++;
        for (i = 1; i < 10; i++)
            count[i] += count[i - 1];
        for (i = n - 1; i >= 0; i--)
        {
            output[count[(arr[i] / exp) % 10] - 1] = arr[i];
            count[(arr[i] / exp) % 10]--;
        }
        for (i = 0; i < n; i++)
            arr[i] = output[i];
    }
    
    void radixsort(int arr[], int n)
    {
        clock_t clockStart;
        clockStart = clock();
    
        int m = getMax(arr, n);
        for (int exp = 1; m / exp > 0; exp *= 10)
            countSort(arr, n, exp);
    
        cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
    }
    
    int StrToInt(string sti) 
    {
        int f;
        stringstream ss(sti); //turn the string into a stream
        ss >> f;
        return f;
    }
    
    int main()
    {
        const int MAX_SIZE = 10;
    
        int arr[ MAX_SIZE ] = { 0 };
    
        //int i = 0;
        //int result = 0;
        string line = "";
    
        ifstream myfile;
        myfile.open("integers2.txt");
        if(!myfile.is_open())
        {
            cerr << "Could not open file!\n";
            return -1;
        }
    
        cout << "Reading integers...\n";
    
        int index = 0;
        //while ( index < SIZE && getline( myfile, line ) )
        while ( index < MAX_SIZE && myfile >> arr[ index ] )
        {
            //getline( myfile, line );
            //result = StrToInt( line );
            //arr[index] = std::stoi( line );
            cout << arr[index] <<"\n";
            index++;
        }
    
        cout << "Sorting integers...\n";
    
        //int n = sizeof(arr) / sizeof(arr[0]);
    
        radixsort( arr, index );
    
        for ( int i = 0; i < index; i++ )
        {
            cout << arr[i] << "\n";
        }
    
        return 0;
    }
    

    几点:

    1. 检查std::stoi 进行字符串到整数的转换;顺便说一句,你不需要这样做。直接这样读:while ( file &gt;&gt; integer )
    2. 需要检查文件是否打开;否则返回错误;在您的情况下,即使文件未打开,其余代码仍然在执行,即 if ( myfile.open() ) { ... } 之后的代码
    3. while( !myfile.eof() ) 是不好的做法。见:Why is iostream::eof inside a loop condition considered wrong?
    4. 您不需要像int n = sizeof(arr) / sizeof(arr[0]); 那样计算大小,因为您已经知道大小。只需为此使用 const
    5. 从文件读取时,您还需要验证数组的最大大小。您应该阅读允许的尺寸。注意out-of-bounds 读/写错误。
    6. 使用&lt;ctime&gt; 而不是&lt;time.h&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2014-05-12
      • 1970-01-01
      相关资源
      最近更新 更多