【问题标题】:In Radix Sort, I get munmap_chunk(): invalid pointer and Aborted (core dumped). Why?在基数排序中,我得到 munmap_chunk(): invalid pointer 和 Aborted (core dumped)。为什么?
【发布时间】:2020-06-14 15:08:59
【问题描述】:

整个程序正确执行后,我在终端收到 munmap_chunk(): invalid pointerAborted (core dumped) 消息。

基数排序功能:

我按以下步骤设计了该功能:

  1. 查找最大值并计算编号。其中的位数。
  2. 运行“d”或否的主循环。位数次。
  3. 数组 C 中的每次频率都计入第 i 个元素。
for(int i = 0 ;i < A.size(); i++){
    int t = (int(A[i]/pow(10,j))%10);
    ++C[t];                                 
}   

  1. 然后是计数排序
  2. 用 B 更新 A 的值。
#include<bits/stdc++.h>
using namespace std;

void Print(vector<int> &A){                         
    for(auto i =A.begin(); i!= A.end(); i++){
        cout << *i << " ";
    }
    cout << endl;
}

void radixSort(vector<int> &A){           
    int k = A[0];
    for(auto i = A.begin(); i!=A.end(); i++){       
        if(*i > k)  k =*i;
    }

    int d =0;
    while(k >0){
        k = k/10;
        d++;                                        
    }
    vector<int> result;
    for(int j =0; j <d; j++)
    {
        vector<int> C(10, 0);               // Making the array Count of k elements with all 0's
        vector<int> B(A.size());            // Output Array     
        for(int i = 0 ;i < A.size(); i++){
            int t = (int(A[i]/pow(10,j))%10);  // for taking ith value
            ++C[t];                           // Counting Frequencies of elements in Input array    
        }                                           
        for(int i=1; i<= C.size(); i++){        // Calculating no of elements occuring before postion i 
            C[i]+= C[i-1];                      // Or Calculating final postion of the value
        }
        for(int i = B.size()-1;i >= 0; i--){
            int t = (int(A[i]/pow(10,j))%10);
            B[C[t]-1] = A[i];                   // Placing the elemsnts from Input Array in Output array accoring to their position     
            --C[t];                             // Decrementing so as to place a same value on left side ( if it Exits)   
        }
        result = A = B;
    }
}

主要功能

int main(){
    vector<int> A;
    srand(time(NULL));
    for(int i =0; i< 10; i++){
        A.push_back(rand()%1000);
    }
    cout << "Input Array : " << endl;;
    Print(A);
    radixSort(A);
    cout << "Output Sorted Array : " << endl;;
    Print(A);
    return 0;
}

【问题讨论】:

  • 在处理整数基数和指数时不要使用powpow 函数是一个可能不准确的浮点函数。

标签: c++ sorting segmentation-fault coredump radix-sort


【解决方案1】:

我在这里看到一个问题,因为 C[10] 被用作索引,它超出了向量的最后一个元素。最简单的解决方法是使 C 1 元素更大,并修复计数到索引的转换循环:

        vector<int> C(11, 0);         // fix (11)
        // ...
        for(int i=1; i <= 10; i++){   // fix ( <= 10)
            C[i]+= C[i-1];
        }

【讨论】:

  • 谢谢!这么多,我没看到!!
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 2020-07-23
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 2020-09-10
相关资源
最近更新 更多