i'm trying to carry out a pascal triangle, and i need to copy an array to an other, i'm currently using the copy function but getting the famous segmentation fault.
here is my code:
#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;
}
I'm getting the same error with memcpy function , can anyone
(before your edition)
The problem appears before the
std::copy
Having
tab and tab1 are not initialized, they do not point to a block of memory used as an array, so the behavior is undefined (a segmentation fault in your case) each time they are dereferenced
Concerning the code about number you probably wanted something like
Warning in
it seems you suppose the first index of an array is 1, while it is 0
A proposal from your code (after your edition) removing undefined behaviors, more some other changes, I commented the modifications.
Compilation and execution :
However in
tab is initialized a lot of times for nothing, it is enough to initialize each entry only one time
std::copy(tab, tab+index, tab1);
is useless because tab1 is never used.It is possible to remove all concerning tab1 and to just have :
An execution under valgrind to check memory accesses and leaks (tab1 removed) :
Also note you miss to print the last element in print
can be