简体   繁体   中英

Class type Segmentation Fault

It has been long time I did not use c++ and I have some basic errors. Can you tell me why I get Segmentation Fault from my generic code? When I use int as a array type, it works perfectly but when I change it with "Trapdoor" type, it gives me Seg Fault.

array<array<int, colN>, rowN> SmartIds::createMatrix() {
    array<array<int, colN> , rowN> a;
    for(int i = 0; i < rowN; i++) {
        a[i] = createTrapdoors();
    }
//sort(a.begin(), a.end());
    return a;
}

Below code generates seg fault

array<array<Trapdoor, colN>, rowN> SmartIds::createMatrix() {
    array<array<Trapdoor, colN> , rowN> a;
    for(int i = 0; i < rowN; i++) {
        a[i] = createTrapdoors();
    }
//sort(a.begin(), a.end());
    return a;
}

I call my function like below;

auto i = createMatrix();

Trapdoor.cpp class

#include "Trapdoor.h"
#include <cryptopp/pwdbased.h>
using namespace std;
Trapdoor::Trapdoor() {
    // TODO Auto-generated constructor stub
    key = nullptr;
    seed = nullptr;
    iv = nullptr;
    counter = 0;
}

Trapdoor::Trapdoor(byte* keyy, byte* ivv) {
    key = keyy;
    seed = keyy;
    iv = ivv;
    counter = 0;
}

Trapdoor::~Trapdoor() {
    // TODO Auto-generated destructor stub
    delete iv;
    delete key;
    delete seed;
}

void Trapdoor::deriveKeywithCounter() {
    SecByteBlock derived(32);
    PKCS5_PBKDF2_HMAC<SHA1> kdf;
    //kdf.DeriveKey(derived.data(), derived.size(), 0, (byte*)b->data(), sizeof(b), NULL, 0, 100);

    memset(iv, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH);
    counter++;

}

int Trapdoor::getCounter() {
    return counter;
}

The Trapdoor class does not have a correct copy-constructor or copy-assignment operator. So when objects are copied by value, the old and the new both have destructor called and pointers are freed twice etc. etc.

It's rarely a good design to have your class be calling delete on things that it did not new . Your code needs to be clear about who is responsible for freeing memory.

Usually, the best solution is to code Trapdoor so that it actually does not require any delete at all; then you do not have to write any special functions. See Rule of three/five/zero . (I will update this post to include a code sample if you show your class definition).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM