【问题标题】:How to resolve segmentation fault如何解决分段错误
【发布时间】:2021-09-16 12:28:39
【问题描述】:

在终端打印输出时出现分段错误。我在网上搜索。并且明白这个故障是因为访问了一个不允许访问的内存位置。但我需要在我的代码中使用指针。所以有什么想法可以解决这个问题。

功能:

void mix_dataset(array<array<int, 20>, 5430>& array_X_dataset, array<int, 5430>& array_Y_dataset) {
size_t len = array_X_dataset.size();
for (size_t i = 0; i < len; ++i) {
    size_t swap_index = rand() % len;  // Random number between 0 and len-1.
    if (i == swap_index)
        continue;

    array<int, 20> data_point{  };
    data_point = array_X_dataset[i];
    array_X_dataset[i] = array_X_dataset[swap_index];
    array_X_dataset[swap_index] = data_point;
    int Y = array_Y_dataset[i];
    array_Y_dataset[i] = array_Y_dataset[swap_index];
    array_Y_dataset[swap_index] = Y;
}
}

主要:

 mix_dataset(array_X_dataset, array_Y_dataset);
 int* array_Y_set = new int[5430];
 int** array_X_set = new int* [5430];
 for (int i = 0; i < 5430; i++) {
        array_X_set[i] = new int[20];
    }
    // copy contents of the mixed std::arrays into plain arrays  
    for (int i = 0; i < 5430; i++) {
        for (int j = 0; j < 20; j++)
            array_X_set[i][j] = array_X_dataset[i][j];
        array_Y_set[i] = array_Y_dataset[i];
    }
      printf("printout the whole dataset after random mixing:\n");
      for (int i = 0; i < 5430; i++) {
          printf(" %d ", i);
          for (int j = 0; j < 20; j++)
              printf(" %d ", array_X_set[i + j * 5430]);
          printf(" %d ", array_Y_set[i]);
          printf("\n");
  
      }

【问题讨论】:

  • array_X_set[i + j * 5430] 那么这里发生了什么?为什么不array_X_set[...][....]
  • 您正在访问array_X_set ,就好像它是一个一维数组[20*5430],而您将它分配为一个指针数组[5430]
  • std::array 确实授予对底层数组的访问权限。可能是“我需要在我的代码中使用指针”是基于误解
  • 至少告诉我们在哪里违规发生!
  • @YvesDaoust 代码打印出这条语句printout the whole dataset after random mixing: 然后它说分段错误

标签: c++ segmentation-fault


【解决方案1】:

printf(" %d ", array_X_set[i + j * 5430]);

-->

printf(" %d ", array_X_set[i][j]);

【讨论】:

  • 感谢您的回复,您的解决方案排除了故障。但是在 Visual Studio 和 Linux 中使用您的修改编译相同的代码时。两次尝试都给了我两个不同的输出。即使我使用了相同的代码。你能解释一下为什么吗?
  • 这几乎可以肯定是因为随机数,对吧?你如何播种兰特?添加srand (98837); 作为主函数中的第一个调用。
  • 我已经将 srand(3) 放入了两个代码中。但还是同样的问题。
  • 为了调试,我还是先检查随机数序列。并不是 100% 保证 rand 会在不同的编译器上返回相同的序列。只需打印出 'rand()' 的值即可查看。如果这是问题所在,那么还有更好的随机数生成器,它们在不同的系统上实际上也是一致的。
猜你喜欢
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
相关资源
最近更新 更多