std::bad_alloc

Hello, i have two structures like this:

1
2
3
4
5
6
7
8
9
struct Rule{
    int a, b, c;
};

struct Transition{
    int from;       
    int to;
    std::vector<Apply> applies;
};


using a std::vector<Transition> with a foreach like this:

1
2
3
for(Transition t : transitions){
/*...*/
}


throw a std::bad_alloc when the transitions are empty, and only while i'm compiling, in debugging mode everything goes fine. The exception is propbably thrown from the allocator in the new operator, but the singularity of the error is weird, i have no idea of the why. Can anybody help me here? thanks for attention
Note that for each iteration of the loop t is a copy of an element in transitions. If you don't want to create copies you should make t a reference. This shouldn't be the problem though because if transitions really is empty no copies should have been made. The problem is probably in some other part of your code that you have not shown.
doing this:

1
2
3
4
5
6
std::cout << "1";
for(Transition t : transitions){
std::cout << "2";
/*...*/
}
std::cout << "3\n";


after the std::bad_alloc message i can see this: "1std::bad_alloc", the second and third cout are not reached.
doing this:

1
2
3
4
5
6
std::cout << "1";
for(Transition t : transitions){
std::cout << "2";
/*...*/
}
std::cout << "3\n";


after the std::bad_alloc error i can see this: "1std::bad_alloc" on the screen, the second and third cout are not reached.
If you use std::cout for debugging you must make sure to flush the stream, otherwise everything that was written might not have been outputted on to the screen when the crash happens.

 
std::cout << "1" << std::flush;

If you also want a newline you can use std::endl instead of std::flush.

EDIT: When I think about it, it might not be necessary in this case because an exception is not the same as an abrupt crash (like segfault) so it will probably flush cout automatically.
Last edited on
yes, added the std::flush, the error persist
yes, added the std::flush, the error persist

Then it stands to reason that the problem occurs on line 2. Perhaps you shouldn't be making copies of your transitions:

for (Transition& t : transitions)
hmm, now it is crashing, but debugging mode still not crash.

EDIT:
since the vector is empty, there is nothing to copy, and even if the t object is created inside the for, all he would do is create another empty vector, as you can see in the structure. So i can't see why a copy would be a problem.
Last edited on
http://www.eelis.net/iso-c++/testcase.xhtml
A testcase that does not reproduce the problem is useless
A testcase consisting of randomly copy&paste'd bits of code that you thought were relevant can obviously not reproduce the problem.


run your code through valgrind
Topic archived. No new replies allowed.