0

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;
}
Güngör Basa
  • 628
  • 2
  • 9
  • 27
  • 2
    Probably `Trapdoor` does not implement value semantics properly. Show the class definition and the constructors/destructor code for `Trapdoor`. – M.M Mar 10 '15 at 05:43
  • I added my Trapdoor.cpp file to the question @MattMcNabb – Güngör Basa Mar 10 '15 at 05:47
  • 2
    @GüngörBasa, see [What is The Rule of Three?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – R Sahu Mar 10 '15 at 05:49

1 Answers1

1

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).

M.M
  • 138,810
  • 21
  • 208
  • 365
  • also, `delete iv;` etc. is almost certainly bugged; space allocated by `new[]` should be deleted with `delete[]` . – M.M Mar 10 '15 at 05:54