logo
down
shadow

getting segmentation fault when copying arrays using std::copy


getting segmentation fault when copying arrays using std::copy

By : smike
Date : October 23 2020, 06:10 PM
Any of those help 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. , (before your edition)
code :
 int *tab;
 int *tab1;
 ...
 tab[i] = tab1[i];
int tab[20];
int tab1[20]
 for(int i=1;i<=index;i++){
#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[0] = 1;
for (int index = 1; index < number; ++index) {
  tab[index] = index;
  print(tab,index);
}
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 $ 
for(int i = 0; i<nbr;i++){
for(int i = 0; i<=nbr;i++){


Share : facebook icon twitter icon
segmentation fault with copying string in c

segmentation fault with copying string in c


By : Chippette
Date : March 29 2020, 07:55 AM
To fix this issue A string literal is constby default. To make it un-const, you must make it an array:
code :
char s[] = "this is my string";
char t[] = "another string";
c++ segmentation fault when copying a matrix

c++ segmentation fault when copying a matrix


By : Ruijie Zhao
Date : March 29 2020, 07:55 AM
it fixes the issue It looks like operator= starts by freeing current memory (ok), allocating memory (but how much should be allocated?) and copy.
If the source size is bigger than destination size you are going to overwrite memory that was not allocated.
Segmentation fault when copying string to

Segmentation fault when copying string to


By : IMAD
Date : March 29 2020, 07:55 AM
hop of those help? Hit there! , AFAICS, you are trying to modify the strings in:
code :
char* nieposortowane[]={"basia", "zosia", "ala", "genowefa"};
#include <stdio.h>
#include <string.h>

const int ROZMIAR=4;
char basia[] = "basia";
char zosia[] = "zosia";
char ala[] = "ala";
char genowefa[] = "genowefa";
char* nieposortowane[]={basia, zosia, ala, genowefa};

int porownaj(char* a, char* b)
{
return strcmp(a,b);
}

void sortowanie(char** tablica, int N)
{
int zamienione, i;
char tmp;

do
{
    zamienione=0; 
    for(i=0;i<N-1;i++)
        if(porownaj(nieposortowane[i], nieposortowane[i+1])>0)
        {

            tmp=**(tablica+i);
            **(tablica+i)=**(tablica+(i+1));
            **(tablica+(i+1))=tmp;

            zamienione=1;
        }
}
while(zamienione);
}

void wypisz(char** tablica, int N)
{
int i=0;
for(i=0;i<N;i++)
    printf("%s\n", *(tablica+i));
}

void odwr(char** tablica, int N)
{
int i, ln, c;
int start, koniec;
char temp;

for(i=0;i<N;i++)
{
    ln = strlen(tablica[i]);
    char slowo[ln];
    strcpy(slowo,*(tablica+i));
    start=0;
    koniec=ln-1;
    for(c=0;c<(ln/2);c++)
    {
        temp =slowo[start];
        slowo[start]=slowo[koniec];
        slowo[koniec]=temp;
        start++;
        koniec--;
    }
    strcpy(*(tablica+i), slowo);
}
}

int main()
{
printf("Przed sortowaniem: \n");
wypisz(nieposortowane, ROZMIAR);

odwr(nieposortowane, ROZMIAR);
wypisz(nieposortowane, ROZMIAR);

sortowanie(nieposortowane, ROZMIAR);
wypisz(nieposortowane, ROZMIAR);
odwr(nieposortowane, ROZMIAR);
wypisz(nieposortowane, ROZMIAR);

printf("Po sortowaniu babelkowym: \n");
wypisz(nieposortowane, ROZMIAR);

return 0;
}
Przed sortowaniem: 
basia
zosia
ala
genowefa
aisab
aisoz
ala
afewoneg
enum { SIZE_NPSW = sizeof(nieposortowane) / sizeof(nieposortowane[0] };

for (i = 0; i < SIZE_NPSW; i++)
    nieposortowane[i] = strdup(nieposortowane[i]);
Segmentation fault while copying the string

Segmentation fault while copying the string


By : Kim Aernoudt
Date : March 29 2020, 07:55 AM
this one helps. I am trying to execute the below code, but for every attempt I am geting a segmentation fault. The problem seems to be coming from the strncpy function used in tokenizing. I a bit new to programming. Please help me debug the code. Please help:
Matrix copying causes segmentation fault

Matrix copying causes segmentation fault


By : Uchiharitz
Date : March 29 2020, 07:55 AM
Hope this helps I must write a function in C that takes in a matrix (src) and 2 integer values(x,y), then gives out a matrix which contains src x by y times. For example , The condition in the loop
Related Posts Related Posts :
  • Compiler error when overriding virtual methods
  • What is the point of function pointers?
  • Which is faster in memory, ints or chars? And file-mapping or chunk reading?
  • ISO file in C++
  • Expected Class-name before { token
  • Can I trust floats or doubles representing integers to retain precision?
  • Qt execute multiple get with QNetworkAccessManager
  • Big and Little endian question
  • Visual Studio 2008 compiles anything in C++ file?
  • C++ pointer to functions, Beginner Question
  • Fastest algorithm for primality test
  • Passing array of pointers to another class
  • Handling macro redefinition without modifying .h files ... C / C++ language
  • Implement SSL with SSPI: How to start?
  • Creating a simple VS2008 visualizer inside autoexp.dat (problem with casting)
  • C++ - Unicode Newline
  • Program crashing with 'std::out_of_range' error
  • Use signed or unsigned char in constructing CString?
  • Parallel execution policies in C++ 17
  • C++ Class Templates (Queue of a class)
  • Convert image into useable byte array in C?
  • pointer to preallocated memory as an input parameter and have the function fill it
  • Animated Image in Win32
  • error on compiling statically linked library created in Qt
  • How to easily pass a very long string to a worker process under Windows?
  • Can a class add friend classes at runtime in C++?
  • C++ priority queue in ascending order by specific method for objects
  • Initialize and declare dynamically multiple variables of random entities in a loop in C++
  • Serializing, integer without libaries , getting weird results
  • Function pointers with default parameters in C++
  • Compilation errors with RapidXML
  • Bad_alloc exception when using new for a struct c++
  • count specific things within a code in c++
  • How to extract 48*48 icon image from resource of an executable file?
  • C++ Convert string (or char*) to wstring (or wchar_t*)
  • C++ include .h includes .cpp with same name as well?
  • Any way in C++ to forward declare a function prototype?
  • boost graph adjacency_list, retrieving a node's parents
  • Copy method optimization in compilers
  • what the problem in this program? it doesn't use the second number, and doesn't print the last line?
  • Need to format character precedence in Strings
  • Cross-Platform Camera API
  • sizeof continues to return 4 instead of actual size
  • String search algorithm used by string::find() c++
  • Two-phase lookup: can I avoid "code bloat"?
  • Strongest cipher available to use with C/C++?
  • Why does my program occasionally segfault when out of memory rather than throwing std::bad_alloc?
  • Firefox XULRunner or TriXul?
  • Does GetSystemInfo (on Windows) always return the number of logical processors?
  • Where is the difference between these code? Shouldn't output be the same?
  • What does it mean mean by "Expected a statement" in C++
  • keybd_event is not working right =(
  • What native C++ profiling tool do you suggest?
  • how to copy char * into a string and vice-versa
  • C++ write to front of file
  • Delphi conversion of C++ header for DVP7010B video card DLL?
  • I keep Getting Control reaches end of non-void function. What am I doing wrong?
  • How to have struct members accessible in different ways
  • Am I abusing Policies?
  • Modern equivalent of BoundsChecker for Visual Studio 2008
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk