【问题标题】:my code compiles fine but shows segmentation fault on submission on geeksforgeeks.....i am unable to identify the problem我的代码编译良好,但在 geeksforgeeks 上提交时显示分段错误.....我无法识别问题
【发布时间】:2021-11-05 03:33:09
【问题描述】:

这是我用于检查集合(a2)是否是另一个(a1)的子集的函数代码。 在主函数中,数组被声明,然后传递给这个 isSubset 函数。 我创建了一个所有元素为 0 的哈希数组,并先将其从 a1 中的元素递增,然后是 a2
现在计算哈希数组中值为 2 的元素。

string isSubset(int a1[], int a2[], int n, int m) {
        int max=a1[0];
        int count=0;
        for(int i=0;i<n;i++){
            if(a1[i]>max){
                max=a1[i];
            }
        }
        int hash[max+1]={0};
        for(int i=0;i<n;i++){
            hash[a1[i]]++;
        }
         for(int i=0;i<m;i++){
             hash[a2[i]]++;
         }
         for(int i=0;i<max+1;i++){
             if(hash[i]==2)
             count++;
         }
    
        if(count==m)
        return "Yes";
        else return "No";
    
    
    }

【问题讨论】:

  • 请提供minimal reproducible example。考虑在调试器中运行代码,以便查看崩溃的位置和原因。
  • 您应该想从数组 a1 和 a2 中获取最大值,但您只能从数组 a1 中获取最大值。程序在执行“hash[a2[i]]++;”时可能“数组越界”

标签: c++ c++14


【解决方案1】:

您有几种可能获得 SIGSEGV:

  1. a1 为 NULL 或 a2 为 NULL
  2. n 大于a1 的大小,所以a1[i] 溢出并读取无效地址
  3. m 大于a1 的大小,所以a1[i] 溢出并读取了无效地址
  4. int hash[max+1]={0}; 需要太大的缓冲区大小 hash 一个不可用的堆栈。您可以在堆中分配hash,也可以在.data 中作为静态分配。或者,您可能希望使用 brk 系统调用来增加堆栈的可用内存。
  5. a2[i] 大于max,这可能导致hash[a2[i]] 中的内存访问溢出。

我强烈建议您了解如何实现hashtable。你可能对linear probingquadratic probingdouble hashingseparate chaining感兴趣。 如果您厌倦了在静态哈希表中重新散列,您可能需要查看 extendible hashinglinear hashing,它们采用本地重新分配而不是全局重新散列。

【讨论】:

  • 好的,现在我明白了.....感谢您的帮助
猜你喜欢
  • 2017-10-16
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多