Declaring and using custom-class vectors - c++

My mate and I have just come accross a problem we couldn't manage to solve just yet.
We have two classes, solution and generation.
solution has a lot of attributes, and generation has, among others, a vector<solution> pool attribute.
The generation class has a generatePool function :
void generation::generatePool(int initsize){
for(int i = 0; i < initsize; i++){
printf("%d\n", i);
pool.push_back(get_randomized_solution(args));
}
}
in which get_randomized_solution itself returns a solution. Problem is, the program compiles but crashes (Segmentation fault) at the push_backline
We've already tried resize and reserve on the pool vector, we also tried using pointers... but it still crashes and now google (and SO) seemingly have gone out of ideas to help us. We've also redefined solution& solution::operator=(const solution&) and a solution::solution() (with no arguments) constructor, which basically returns an empty solution. Where do you think the problem comes from ?
EDIT:
Here's the get_randomized_solution method:
solution get_randomized_solution(int size, int rcap, int rcom, bool randomized){
solution sol = solution(size, rcap, rcom);
vector< pair<int,int> > cibles;
for(int i = 0; i < size; i++){
for(int j = (i==0) ? 1 : 0; j < size; j++){
cibles.push_back(make_pair(i, j));
}
}
srand(rand());
if(randomized) random_shuffle(cibles.begin(), cibles.end());
for(int k = 0; k < cibles.size(); k++){
if(sol.removeCaptor(cibles[k])){
if(!sol.realisable()){
sol.addCaptor(cibles[k]);
}
}
}
return sol;
}
More complete code: https://codeshare.io/2jLnzB

Well that was indeed get_random_solution, in which there was a size = size line which caused the bug. Really sorry for useless posting.

Related

vector to array and array size in c++

I have a struct:
struct xyz{
int x,y,z;
};
and I initialize a struct xyz type vector:
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
for (int k = 0; k < N; k++)
{
v.x=i;
v.y=j;
v.z=k;
vect.push_back(v);
}
}
}
then I want to transform that vector to array because array is 2 time faster than vector to manipulate, so I do
xyz arr[vect.size()];
std::copy(vect.begin(), vect.end(), arr);
when I run this program it shows me segmentation fault which I think is because vect.size() is too large.
So I am wondering is there any way to convert that large size vector to array without that problem.
I appreciate for any help
My overly pedantic comment got too big, so instead I'll try to make this a somewhat roundabout answer. The short answer is probably just to stick with vector but make sure to use reserve; oh, and benchmark.
You didn't say what compiler or C++ version you're using, so I'll just go with my current gcc.godbolt.org default of gcc 4.9.2, C++14. I'm also assuming that you really want this as a 1-dimension array, rather than the more natural (for your example) 3.
If you know N at compile time, you could do something like this (assuming I got the array offset calculation correct):
#include <array>
...
std::array<xyz, N*N*N> xyzs;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++) {
xyzs[i*N*N+j*N+k] = {i, j, k};
}
}
}
The biggest downsides, IMO:
error-prone offset calculation
depending on N, where the code is run, etc, this can blow the stack
On the compilers I tried this on, the optimizers seem to understand that we're moving through the array in contiguous order, and the generated machine code is more sensible, but it could also be written like so, if you prefer:
#include <array>
...
std::array<xyz, N*N*N> xyzs;
auto p = xyzs.data();
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
(*p++) = {i, j, k};
}
}
}
Of course, if you actually know N at compile time, and it won't blow the stack, you might consider a 3-dimensional array xyz xyzs[N][N][N]; since this might be more natural for the way these things are being ultimately being used.
As pointed out in comments, variable length arrays aren't legal C++, but they are legal in C99; if you don't know N at compile time you should be allocating off the heap.
A vector and an array will wind up being identical in terms memory layout; they differ in that vector allocates memory from the heap, and the array (as you are writing it) would be on the stack. The only recommendation I'd make is to call reserve before entering your loop:
vect.reserve(N*N*N);
This means you'll only be doing a single memory allocation up front, rather than grow-and-copy mechanism that you'll get from a default constructed vector.
Assuming xyz is as simple as you declare here, you could also do something like the second example above:
std::vector<xyz> xyzs{N*N*N};
auto p = xyzs.data();
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
(*p++) = {i, j, k};
}
}
}
You lose the safety of push_back, and it is less efficient if xyz default constructor needs to do anything (like if xyz members were changed to have default values).
Having said all that, you really should benchmark. But then, you should probably be benchmarking the code that ultimately uses this array, rather than the code to construct it; I'd have other concerns if construction was dominating usage.

Accessing an object from a vector of object pointers

This is a bit code i'm having trouble with:
int pressedKey = event.getNativeKeyCode();
for (int i=0; i <= AllTriggerPads.size() ;i++) {
if (AllTriggerPads[i]->get_key() == pressedKey){
AllTriggerPads[i]->mBufferPlayerNode->start();
}
}
the get_key() is getting a EXC_BAD_ACCESS (Code=1, ...) Error.
I seem to have a referencing problem. I am using almost the same code in the mouseDown and the fileDrop function:
for (int i=0; i < AllTriggerPads.size() ; i++) {
if (AllTriggerPads[i]->mRect.contains(event.getPos())) {
AllTriggerPads[i]->mBufferPlayerNode->start();
}
}
This works fine!
Sooooo, i guess i am using the AllTriggerPads vector (of obj pointers) not correctly. So I CAN use AllTriggerPads[i]->mRect.contains(event.getPos())
but I CANT use AllTriggerPads[i]->get_key(). And I CANT access the value itself by AllTriggerPads[i]->key
I have tried it with AllTriggerPads.at(i) but then i get an out of range error which makes me wonder even more.
The AlltriggerPads was initialized with
vector<TriggerPad*> AllTriggerPads;
So how can I access the key member?
You are having an off-by-one error.
for (int i=0; i <= AllTriggerPads.size() ;i++)
replace with
for (int i=0; i < AllTriggerPads.size(); ++i)
(The ++ thing is irrelevant, it's just better practice to always use pre-increment)
You are trying to access an array element which doesn't exist. That's why it throws EXC_BAD_ACCESS. Change the for loop conditional to
for (int i = 0; i < AllTriggerPads.size(); ++i) {
if (AllTriggerPads[i]->get_key() == pressedKey) {
AllTriggerPads[i]->mBufferPlayerNode->start();
}
}
or if C++11 support is enabled, simplify it to
for (auto i : AllTriggerPads) {
if (i->get_key() == pressedKey) {
i->mBufferPlayerNode->start();
}
}

C++ heap corruption on new

I'm writing simple ANN (neural network) for functions' approximation. I got crash with message: "Heap corrupted". I found few advices how to resolve it, but nothing help.
I got error at first line of this function:
void LU(double** A, double** &L, double** &U, int s){
U = new double*[s];
L = new double*[s];
for (int i = 0; i < s; i++){
U[i] = new double[s];
L[i] = new double[s];
for (int j = 0; j < s; j++)
U[i][j] = A[i][j];
}
for (int i = 0, j = 0; i < s; i = ++j){
L[i][j] = 1;
for (int k = i + 1; k < s - 1; k++){
L[k][j] = U[k][j] / U[i][j];
double* vec_t = mul(U[i], L[k][j], s);
for (int z = 0; z < s; z++)
U[k][z] = U[k][z] - vec_t[z];
delete[] vec_t;
}
}
};
As I understood from debagger's information: two arrays (U and L) has been passed to function with some addresses in memory. And it's quite strange because I didn't initialize it. I call this function two times and first time it works nicely (ok, at least it works), but at second call it crashes. I have no idea how to resolve it.
There is link to whole project: CLICK
I'm working in MS Visual Studio 2013 under Windows 7 x64.
UPDATE
According to some commentaries below I should provide some additive information.
First of all, sorry for quality of code. I wrote it only for myself for 2 days.
Second, when I said "at second call", I mean that first I call LU when I need to get determinant of S (I use LU decomposition fot this) and it working without any crashes. Second call it's when I trying to get inverse of matrix (the same, S). And when I call detLU at [0, 0] point of matrix (to get cofactor) I got this crash.
Third, if I get information from debagger correctly, arrays L and U passes in function at second call with already defined memory's addresses. I can't understand why, becouse before LU call I have just wrote "double** L; double** U;" without any initialization.
I can try provide some additional debug information or some tests, if somebody explain me what exactly I have to do.
The point you get a heap corruption error/crash is typically just the symptom of an actual heap overflow/underflow or other memory error at some other time/point in the past. This is why heap corruptions can be difficult to track down.
You have a lot of code and all the double-pointers are difficult to track but I did notice one potential issue:
double** initInWeights(double f, int h, int w) {
double** W = new double*[h];
for (int i = 0; i < 10; i++) {
W[i] = new double[w];
The loop will overflow W[] if h is less than 10. Chances are that somewhere in your code you have a buffer overflow/underflow or are using memory after it is freed. The complexity and design of your code makes it difficult to pinpoint at a glance.
Is there a reason you are using raw double-pointers instead of simply std::vector<std::vector<double>>? This would remove all your manual memory management code, making your code shorter, simpler, and more importantly remove the heap corruption issue.
Barring that you should double-check that all manually allocated memory is the correct size and access loops can never go out-of-bounds.
Update -- I think your problem may lie with a buffer overflow in the extract() function in matrix.cpp:
double** extract(double** mat, int s, int col, int row)
{
double** ext = new double*[s - 1];
for (int i = 0; i < s - 1; i++)
{
ext[i] = new double[s - 1];
}
int ext_c = 0, ext_r = 0;
for (int i = 0; i < s; i++)
{
if (i != row)
{
for (int j = 0; j < s; j++)
{ // Overflow on ext_c here
if (j != col) ext[ext_r][ext_c++] = mat[i][j];
}
ext_r++;
}
}
return ext;
};
You never reset ext_c so it simply keeps increasing in size up to (s-1)*(s-1) which obviously overflows the ext[] array. To fix this you simply need to change the inner loop definition to:
for (int j = 0, ext_c = 0; j < s; j++)
At least that one change lets me run your project without any heap corruption errors.

C++ Error C2100: Illegal Indirection--bubbleSort

I am trying to send a vector into a bubbleSort function to organize numbers from max to min as they are produced one by one, but I am getting the "C2100: Illegal indirection" warning. Can someone please help me out?
private: void bubbleSort(vector<int> &matrixPtr)
{
int temp;
int numLength = *matrixPtr.size( );//length of vector
for (int i = 1; (i <= numLength);i++)
{
for (int j=0; j < (numLength -1); j++)
{
if (*matrixPtr[j+1] > *matrixPtr[j])
{
temp = *matrixPtr[j];//Swap elements
*matrixPtr[j] = *matrixPtr[j+1];
*matrixPtr[j+1] = temp;
}
}
}
}
The bubbleSort is drawn from another function ahead of it:
bubbleSort(&output);//pass to bubble sort
for (int rows=0;rows<creation->getZeroRows();rows++)
{
for (int cols=0;cols<creation->getCols();cols++)
{
txt_DisplayRowSum->Text= String::Concat(txt_DisplayRowSum->Text, (*creation->zeroArrayPtr)[rows][cols]," ");
}
txt_DisplayRowSum->Text+=" \n";
}
Thank you for your help in advance
You are incorrectly using references.
Instead of *matrixPtr.size( ) you need matrixPtr.size(), and everywhere else in the function you do not need the * when referring to matrixPtr. Also, when passing the vector to the function, you should pass just output and not &output.
You should not and can not use references like pointers. While similar, they're different in several important ways. I also recommend this question for a good summary of those differences.

vector.push_back() crashes

I have a problem while working with vectors of a class. I have tried whittling away at the code as much as possible, leaving me with the code below. Yet, after doing this, I still cannot figure out why my program is crashing. I come from a world of VBA and my C++ debugging skills are poor to say the least and I apologize for that up front. Any guidance to improve my ability here will be gladly accepted.
My class:
class Tester {
public:
int varA;
int varB;
Tester() {
varA = 1;
varB = 1;
}
Tester(Tester& P1, Tester& P2) {
varA = P1.varA + P2.varA;
varB = P1.varB + P2.varB;
}
Tester(const Tester &Source) {
varA = Source.varA;
varB = Source.varB;
}
};
My test mains:
Does not work:
int main() {
std::vector < Tester > BreakIt;
for (int i = 0; i < 2500; i++) {
Tester newTester;
BreakIt.push_back(newTester);
Tester& tempTester = BreakIt.at(0);
for (int j = 0; j < 4; j++) {
BreakIt.push_back(Tester(newTester, tempTester)); //This is where it crashes.
}
}
return 0;
}
Does work:
int main() {
std::vector < Tester > BreakIt;
Tester newTester;
BreakIt.push_back(newTester);
for (int i = 0; i < 2500; i++) {
Tester& tempTester = BreakIt.at(0);
for (int j = 0; j < 4; j++) {
BreakIt.push_back(Tester(newTester, tempTester));
}
}
return 0;
}
Does work:
int main() {
std::vector < Tester > BreakIt;
for (int i = 0; i < 2500; i++) {
Tester newTester;
BreakIt.push_back(newTester);
Tester& tempTester = BreakIt.at(0);
}
return 0;
}
The push_back() line that breaks does run a few times before the crash. It seems that when I change certain things around and recompile, the point at which it crashes changes (i.e. 20 times through the main loop vs. 175 times vs. 1000 times). However, once I've compiled, it will typically run through the the same iteration each time before crashing.
I suspect that this is some kind of 'undefined behavior' but from where I'm not sure.
Can someone please help me identify why BreakIt.push_back(Tester(newTester, tempTester)); does not work where I want it to?
You're right, there is undefined behaviour.
You're taking a reference to BreakIt.at(0); however this object is no longer guaranteed to exist after you've done a push_back, because if the vector grows, all of the contents are typically copied, and the originals deleted.
From http://www.cplusplus.com/reference/stl/vector/push_back/ (not the world's best reference):
Reallocations invalidate all previously obtained iterators, references and pointers.
For me, it was the issue with the MinGW version (MinGW g++ 6.3.0) which I updated to 7.2.0 from https://mingw-w64.org/doku.php/download.
Now it's working fine.