【问题标题】:Segmentation fault while using vector in C++?在 C++ 中使用向量时出现分段错误?
【发布时间】:2017-05-15 13:30:28
【问题描述】:

为什么我在以下代码中遇到分段错误? 此代码以第一个元素为 0 的数组 s 开始。然后是元素与 s 互补的数组 t,然后将 t 附加到 s 直到大小大于 1000。 然后用户输入查询的数量,并打印数组 s 的索引为 x 的元素。

#include <bits/stdc++.h>

using namespace std;

int duplication(int x){
     // Complete this function
     vector <int> s;
     vector <int> t;
     int i=0,j;
     int n=0;
     s.push_back(n);
     while(true){
         t.clear();
         for(j=0;j<s.size();j++){
             int k = 1 - s.at(j);
             t.push_back(k);
         }
        for(j=0;j<s.size();j++){
             s.push_back(t[j]);
        }
        if(s.size()>1000) break;
    }
    i=s[x];
    return i;
}

int main() {
    int q;
    cin >> q;
    for(int a0 = 0; a0 < q; a0++){
        int x;
        cin >> x;
        int result = duplication(x);
        cout << result << endl;
    }
    return 0;
}

【问题讨论】:

  • 你的第二个 forloop 不应该检查 t 的大小而不是 s 吗?
  • 您遇到了段错误,因为您不知道如何使用调试器一次一行地单步执行您的代码,以便检查所有变量的内容,并检查您的程序执行时的逻辑,以便识别错误并自行修复。这就是为什么您仍然遇到段错误。
  • 你的第二个for 循环是错误的。您在检查size 的同时添加到s,并且当您在循环主体中添加到s 时,for 循环将永远不会退出。
  • 传入任何 x > 1000 的值也有可能发生分段,

标签: c++ vector segmentation-fault


【解决方案1】:

对于第二个循环,我认为应该是

 for(j=0;j<t.size();j++)

另外,i=s[x] 可能应该检查x 是否在s 的索引范围内。

【讨论】:

  • 第二个循环很好,因为第一个循环根据“s”的大小调整“t”的大小。当然不是一个好的做法,但它是有效的。
  • @AlexG 我也有同样的想法,但请注意第二个循环修改了s 的大小。
  • @NathanOliver 是的。刚刚也看到了。
【解决方案2】:

您的问题是第二个 for 循环。

for(j=0;j<s.size();j++){
    int k = 1 - s.at(j);
    t.push_back(k);
}

for(j=0;j<s.size();j++){ // First iteration size of S is 1, Size of T is 1
    s.push_back(t[j]);   // Size of s is now 2.
                         // Loop iteration comes around again j = 1 which is < 2
                         // t has a size of 1, you are accessing the 2nd index
                         // which is memory that you do not own.
}

s 的大小将在每次迭代中得到解决,因为它在不断变化,您可以存储一个变量来跟踪 s 的大小或使用 t 的大小,但要小心,如果 s 的大小越来越大t 并且您正在存储 s 的大小,您将遇到同样的问题。

在此处阅读分段错误: What is a segmentation fault?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多