c++ - 使用 std::copy 复制数组时出现段错误

标签 c++ arrays stdcopy

我正在尝试执行一个 Pascal 三角形,我需要将一个数组复制到另一个数组,我目前正在使用复制功能,但遇到了著名的段错误。

这是我的代码:

    #include <iostream>
    #include <algorithm> 
    #include <cstring>

    using namespace std;

    void print(const int *tab, const int &nbr){
        for(int i = 0; i<nbr;i++){
          cout << tab[i];
         }

        cout << endl;
     }


     int main()
     {
       int *tab;
       int *tab1;
       int index = 0;
       cout << "enter a number less than or equal to 20!" << endl;
       int number = 40;
       while(number > 20){
         cin >> number;
         cout << endl;
       }

       int a = 1;

       while(index < number){
         tab[0] = 1;
         for(int i=1;i<=index;i++){
            tab[i] = i;
         }
         print(tab,index);
         std::copy(tab,tab+index,tab1);
         index++;
       }

       return 0;
     }

我在使用 memcpy 函数时遇到了同样的错误,任何人都可以吗

最佳答案

(在您的版本之前)

getting segmentation fault when copying arrays using std::copy

问题出现在std::copy

之前

拥有

 int *tab;
 int *tab1;
 ...
 tab[i] = tab1[i];

tabtab1 未初始化,它们不指向用作数组的内存块,因此行为未定义(在您的情况下是段错误) 每次它们被取消引用时

关于关于number 的代码,你可能想要类似的东西

int tab[20];
int tab1[20]

警告在

 for(int i=1;i<=index;i++){

你似乎假设数组的第一个索引是 1,而它是 0


您的代码(在您的版本之后)删除未定义行为的建议,还有一些其他更改,我评论了这些修改。

#include <iostream>
#include <algorithm> 
#include <cstring>

using namespace std;

void print(const int *tab, const int &nbr){
  for(int i = 0; i<nbr;i++){
    cout << tab[i] << ' '; // add a space to separate numbers 
  }

  cout << endl;
}

int main()
{
  int number;

  do { // your case it typically a "do while"
    // print moved inside to clearly indicate the expected input
    // even after a number invalid
    // and also request a  number > 0 else no sence after
    cout << "enter a number between 1 and 20!" << endl;
    if (!(cin >> number)) { // detect the error else if a non number you loop forever
      cerr << "invalid input" << endl;
      cin.clear(); // clear the error

      // bypass invalid input
      string s;

      if (! (cin >> s)) {
        // EOF !
        return -1;
      }
      number = 0; // to reloop
    }
  } while ((number > 20) || (number <= 0));

  int * tab = new int[number]; // added missing initialization
  int * tab1 = new int[number]; // added missing initialization

  for (int index = 0; index < number; ++index) {
    tab[0] = 1;
    for(int i=1; i<=index; i++) {
      tab[i] = i;
    }
    print(tab,index);
    std::copy(tab, tab+index, tab1);
  }

  // free resources
  delete [] tab;
  delete [] tab1;

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall cp.cc
pi@raspberrypi:/tmp $ ./a.out
enter a number between 1 and 20!
aze
invalid input
enter a number between 1 and 20!
-1
enter a number between 1 and 20!
21
enter a number between 1 and 20!
20

1 
1 1 
1 1 2 
1 1 2 3 
1 1 2 3 4 
1 1 2 3 4 5 
1 1 2 3 4 5 6 
1 1 2 3 4 5 6 7 
1 1 2 3 4 5 6 7 8 
1 1 2 3 4 5 6 7 8 9 
1 1 2 3 4 5 6 7 8 9 10 
1 1 2 3 4 5 6 7 8 9 10 11 
1 1 2 3 4 5 6 7 8 9 10 11 12 
1 1 2 3 4 5 6 7 8 9 10 11 12 13 
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 
pi@raspberrypi:/tmp $ 

然而在

for (int index = 0; index < number; ++index) {
  tab[0] = 1;
  for(int i=1; i<=index; i++) {
    tab[i] = i;
  }
  print(tab,index);
  std::copy(tab, tab+index, tab1);
}

tab白白初始化了很多次,每个entry只初始化一次就够了

std::copy(tab, tab+index, tab1); 没用,因为 tab1 从未使用过。

可以删除所有与 tab1 相关的内容,只需要:

tab[0] = 1;
for (int index = 1; index < number; ++index) {
  tab[index] = index;
  print(tab,index);
}

valgrind 下执行以检查内存访问和泄漏(已删除 tab1):

pi@raspberrypi:/tmp $ valgrind ./a.out
==16633== Memcheck, a memory error detector
==16633== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16633== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==16633== Command: ./a.out
==16633== 
enter a number between 1 and 20!
10
1 
1 1 
1 1 2 
1 1 2 3 
1 1 2 3 4 
1 1 2 3 4 5 
1 1 2 3 4 5 6 
1 1 2 3 4 5 6 7 
1 1 2 3 4 5 6 7 8 
==16633== 
==16633== HEAP SUMMARY:
==16633==     in use at exit: 0 bytes in 0 blocks
==16633==   total heap usage: 4 allocs, 4 frees, 22,312 bytes allocated
==16633== 
==16633== All heap blocks were freed -- no leaks are possible
==16633== 
==16633== For counts of detected and suppressed errors, rerun with: -v
==16633== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $ 

另请注意,您错过了打印print

中的最后一个元素
for(int i = 0; i<nbr;i++){

可以

for(int i = 0; i<=nbr;i++){

关于c++ - 使用 std::copy 复制数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045325/

相关文章:

c++ - Windows Task Scheduler : IAction. QueryInterface() 返回一个错误我找不到定义

c++ - 在 Qt Creator 中利用 poppler - 帮助

Python:在嵌套在 for 循环中的 if 语句中访问索引号

在数组中收集相同的单词,C

c++ - 从结构到 std::vector 的二进制复制数据

c++ - 在函数中添加参数时重建动态库

c++ - 是否允许在后缀运算符++中命名参数?

arrays - 字符串快速追加到数组

c++ - 在结构数组上使用 C++ std::copy