I'm building a library consisting of a class (MyTotp
) that has an object as property (Profile
).
In the main
test function I built a vector of Profile
objects and a for loop
which iterates through vector assigning the object to the MyTotp
property and calculating the result.
The program compiles correctly. When it is run the first loop is executed correctly but the second one raise a segmentation fault (core dump)
.
Debugging the program I noticed that the error appears after the second re-allocation of memory (required_size
may change (and it does into the test) in each loop) for array uint8_t * secret
as pointed into the code. I thought the re-allocation was the cause for the memory failure, but I can't exclude anything
Below the significant code...
MyTotp.h
class buzztotp {
public:
[...]
Profile profile;
[...]
};
}
MyTotp.cpp
void MyTotp::getPaddedSecret(uint8_t * out) {
uint8_t* secret = this->profile.getSecret();
uint32_t secret_len = this->profile.getSecretLen();
for (int i = 0; i < this->required_size; i++) {
int index = i % secret_len;
out[i] = secret[index];
}
delete[] secret; secret = NULL;
}
uint32_t MyTotp::generateTOTP() {
this->preprocess(); //It calculates, according to profile properties, this->required_size
uint8_t* secret = new uint8_t[this->required_size]; //Here the memory error while debugging
this->getPaddedSecret(secret);
[...]
delete[] secret; secret = NULL;
return (...);
}
Profile.h
uint8_t* Profile::getSecret() const {
uint8_t* out;
out = new uint8_t[this->secret_len]; //#Edit1 - Error now here
//memcpy(out, this->secret, this->secret_len*sizeof(uint8_t));
std::copy(this->secret_vector.begin(), this->secret_vector.end(), out);
return out;
}
main.cpp
int main(void) {
currentDir();
XmlResourceManager xmlresman;
xmlresman.setFilename(std::string("...myfile.xml"));
/*
* Here the vector<Profile> xmlresman::profiles is built as:
*
* Profile __profile;
* [...]
* this->profiles.push_back(__profile);
*/
xmlresman.parseXml();
for (unsigned int i = 0; i < xmlresman.profiles.size(); i++) {
MyTotp mytotp;
buzztotp.profile = xmlresman.profiles[i];
try {
std::cout << "TOTP: " << mytotp.generateTOTP() << std::endl;
} catch (std::string str) {
std::cerr << str << std::endl;
}
//mytotp.~mytotp();
}
return 0;
}
Any suggestions?
Edit1
I used two strategies (I can't figure the best out) for elaborating a uint8_t*
by a function: generating/instantiating it into the parent block and passing it to the function as an argument OR returning a generated/instantiated pointer into the function itself. Running the debug again it seems the error is at the re-allocation of out
into Profile::getSecret()
. I'm starting to get confused about the behaviour of the program run.
The explicit destructor (mytotp
) into the main loop was only a past try: it is a misprint, completely useless by now.
Edit2
Cancelling the explicit constructor seems to solve the problem.