mercredi 24 octobre 2018

C++ segfault sometimes but

This program gives me segfault sometimes. I wanted to compare copy ctor with move ctor on speed. What is interesting it never throws segfault when running in gdb.

#include <iostream>
 #include <cstdlib>
 #include <ctime>
using namespace std;

 class Alma{
     protected:
        int* v;
        int size;
     public:
        void p_r(void);
        void fill_r(void);
        Alma(int size){
            this->size=size;
            v= (int*) malloc(size * sizeof(int));
        }
        ~Alma(){
            delete v ;
        } 
        Alma(const Alma& a){
            clock_t begin = clock();
            v= (int*) malloc(size * sizeof(int));
            size=a.size;
            for(int i =0; i< size;i++ ){
                 v[i]=a.v[i];
            }
            clock_t end = clock();
            double ms = double(end - begin) / CLOCKS_PER_SEC;
            cout << "copy / time:"<< ms << endl;
        }
};
class Korte:public Alma{
    public:
        Korte(int size):Alma(size){}

    Korte& operator=(Korte&& a){
            clock_t begin = clock();
             v=a.v;
             size=a.size;
             a.size=0;
             a.v=nullptr;
             clock_t end = clock();
             double ms = double(end - begin) / CLOCKS_PER_SEC;
             cout << "move / time:"<< ms << endl;
            return *this;
         }
};
void Alma::fill_r(){
    for(int i =0; i< size;i++ ){    
        v[i]=rand();
    }
}
int main(){
    Alma a(20000000);
    a.fill_r();
    Alma b = a;
    Korte k(20000000);
    k.fill_r();
    Korte k2(2);
    k2=move(k);
    return 0;
}

At first I wanted to sort vectors but vectors gave me segfault when I used too many elements.(tens of thousands) even with setting the initial size. So I just wrote this. What is the problem?

Aucun commentaire:

Enregistrer un commentaire