very weird hang at a for loop initialization - c++

I have a very weird bug that I can't seem to figure out. I have narrowed it down to a small section of code (unless the compiler is reordering my statements, which I don't believe is true).
...
std::cout << "here"<< std::endl;
std::vector<int>::iterator n_iter;
std::vector<int>::iterator l_iter;
std::cout << "here?" << std::endl;
for(n_iter = n.begin(), std::cout << "not here" ; std::cout << "or here" && n_iter < n.end(); n_iter++)
{
std::cout << "do i get to the n loop?";
...
}
When I run this, I see the first "here", the second "here?", but I don't get the "not here" or the "or here" output. And I definitely don't get the "do i get to the n loop?".
The weird thing is that my program is working (it is almost using up an entire cpu core... ), but it doesn't finish, it just hangs.
I've tried using clang++ and g++, and I'm not using any optimizations. I have the boost library installed (and am using the boost_program_options part of it), along with armadillo. But I don't think the compiler should be reordering things...
It happens with or without the cout calls inside the for loop declaration, and it doesn't just skip the loop.
The vector "n" has a length of at least 1, and is given by a boost_program_options call.
Any ideas?

The first thing you should try is to output std::endl after each string. This flushes the buffer for the output.

The following program (which has some extra newlines that yours didn't):
#include <string>
#include <iostream>
#include <vector>
int main() {
std::vector<int> n;
n.push_back(3);
n.push_back(3);
n.push_back(3);
std::cout << "here"<< std::endl;
std::vector<int>::iterator n_iter;
std::vector<int>::iterator l_iter;
std::cout << "here?" << std::endl;
for(n_iter = n.begin(), std::cout << "not here\n" ; std::cout << "or here\n" && n_iter < n.end(); n_iter++)
{
std::cout << "do i get to the n loop?\n";
}
}
Has the following output:
[5:02pm][wlynch#orange /tmp] make foo
g++ foo.cc -o foo
[5:02pm][wlynch#orange /tmp] ./foo
here
here?
not here
or here
do i get to the n loop?
or here
do i get to the n loop?
or here
do i get to the n loop?
or here
This appears to be what you expect, so I'm not sure where you are having issues on your end, but it may be in skipped code.

Related

No output from cout When assertion Fails

Cout fails to print anything even though it is on a line before the assertion. It behaves so when I compile and run the code through linux shell. But it prints when tried with an online compiler.
ex-
for(int i =0;i<n;i++)
{ std::cout << "should print";
assert(2==1);
}
I should see "should print" at least once right? And why the different behaviour through online compilers?
Output from std::cout is probably being buffered here. Explicitly emptying the buffer should make it print before the assertion fails. (std::endl,std::flush, std::unitbuf manipulators should do)
for(int i =0;i<n;i++)
{ std::cout << "should print" << std::endl;
assert(2==1);
}

Postpone standard output in the end

Many warning messages (via std::cout) might be printed out during the process. Is there a way to postpone the printing of the warning messaged in the end of the program? There are huge amount of the processing information will be printed. I'm planing to have all the warnings together in the end rather than scattered around.
More background:
code is already there.
there are about 50 warning messages within the code (in case if there is some sort of delay( ) function, I don't want to add 50 times, would be nice if there is an globally delaye/postpone function for stand output)
Thanks
One way to do it is to send everything to a stringstream, and then print at the end.
For example:
#include <iostream>
#include <sstream>
int main(){
int i = 5, j = 4;
std::stringstream ss;
std::cout << i * j << std::endl;
ss << "success" << std::endl;
std::cout << j + i * i + j << std::endl;
ss << "failure" << std::endl;
std::cout << ss.str() << std::endl;
return 0;
}
Output:
20
33
success
failure
If you're just trying to delay all printing of std::cout what you can do is redirect standard out to a string stream that acts as a buffer. It's pretty simple and avoids all of the dup, dup2, and piping stuff that one might be inclined to try.
#include <sstream>
// Make a buffer for all of your output
std::stringstream buffer;
// Copy std::cout since we're going to replace it temporarily
std::streambuf normal_cout = std::cout.rdbuf();
// Replace std::cout with your bufffer
std::cout.rdbuf(buffer.rdbuf());
// Now your program runs and does its thing writing to std::cout
std::cout << "Additional errors or details" << std::endl;
// Now restore std::cout
std::cout.rdbuf(normal_cout);
// Print the stuff you buffered
std::cout << buffer.str() << std::endl;
Also in the future, you should really use a buffer for errors from the start OR at a minimum write errors and logging to std::cerr so that your normal runtime print outs aren't cluttered with errors.

Variable getting destroyed before calling lambda

I'm trying to build a lambda that wraps some input functions with some pre/post actions.
My code works fine and pre/post actions get called correctly if I try to wrap a regular function/lambda.
However, when I try to apply my decorating lambda to a function that it produced before, my program crashes after complaining that the inner function was freed at some point (this is confirmed by valgrind).
What puzzles me is that the crash depends on the compiler: the code works perfectly fine with Xcode 6 clang (clang-3.6 based), but crashes on linux using clang++-3.6 and g++4.8.4.
I've made a small program that reproduces the behaviour:
#include <iostream>
#include <string>
#include <functional>
using namespace std;
typedef function<void(void)> NestedFn;
int main()
{
// Create a cfunction
auto lambdaFactory = [&](string title, NestedFn nestedFunc)
{
// title is copied to the new lambda
return [&, title]() {
cerr << "------------ START -----------" << endl;
cerr << "Inside: " << title << endl;
nestedFunc();
cerr << "------------- END ------------" << endl;
};
}
auto l1 = lambdaFactory("1", []() { cerr << "\tNest (1)" << endl; });
auto l2 = lambdaFactory("2", []() { cerr << "\tNest (2)" << endl; });
l1(); // Works ok, displays, START, 1, END
l2(); // Same here
auto dobble = lambdaFactory("Dobble", l1);
dobble(); // Display START, Inside Dobble, START,
// then crashes when trying to execute nestedFunc(), ie l1()
}
What did I get wrong in the variable scope management ? And is there any reason for this program not crashing using Apple's LLVM ?
EDIT
For the record, here is the correct lambdaFactory after the correction suggested by T.C. :
auto lambdaFactory = [&](string title, NestedFn nestedFunc)
{
return [&, title, nestedFunc]() {
cerr << "------------ START -----------" << endl;
cerr << "Inside: " << title << endl;
nestedFunc();
cerr << "------------- END ------------" << endl;
};
};
The lambda returned by a call to lambdaFactory captures nestedFunc by reference, but nestedFunc is a function argument passed by value, so it goes out of scope as soon as the call to lambdaFactory returns, resulting in a dangling reference.
And is there any reason for this program not crashing using Apple's LLVM ?
Undefined behavior is undefined. You are also likely using two different standard library implementations (libc++ on Mac/libstdc++ on linux), so there are likely differences in how everything is laid out etc.

Differences between std::set and boost::ptr_set?

I've changed some code to convert a std::set to a boost::ptr_set. However, the code doesn't compile; the problem is that I'm assuming that the return value from a ptr_set insert is the same as a set insert (a pair<myIter, bool>). After an hour on Google I found this, and it turns out that the return value from a ptr_set insert appears to be a bool.
Is there any definitive documentation on the differences between the ptr containers and the std containers? I haven't found anything on the boost website, but maybe I'm just being dumb...
EDIT
Ok - what was confusing me was that this code
t.insert(s.release(s.begin()));
p = t.insert(s.release(s.begin()));
reports no error on the first line on gcc, but reports no match for operator= on the second line, so I thought the error was in the return type. However, if you comment out the second line, the first line is then reported as an error (release doesn't return an iterator). My confusion was compounded by the link I posted, in which ptr_container's author states that "insert() in ptr_set<> returns bool". However, reading on down the link it becomes obvious that the code hadn't been finished at the time. Thanks Kerrek.
The following code works as expected, and the interface is the same as for std::set::insert():
#include <boost/ptr_container/ptr_set.hpp>
#include <boost/assign/ptr_list_inserter.hpp>
#include <iostream>
int main()
{
boost::ptr_set<int> s;
{
auto p = s.insert(new int(4));
std::cout << "Element " << *p.first << (p.second ? " inserted" : " already existed") << std::endl;
}
{
auto p = s.insert(new int(4));
std::cout << "Element " << *p.first << (p.second ? " inserted" : " already existed") << std::endl;
}
boost::assign::ptr_insert(s)(1)(2)(3)(4);
for (auto it = s.begin(), end = s.end(); it != end; ++it) { std::cout << *it << "\n"; }
}
The documentation is perhaps not the easiest to navigate, but it's all there. You should look for the "set adapter", though, perhaps that's not entirely obvious.

Strange behaviour with std::vector

consider this segment of codes:
std::vector<int> vecList;
...populate 3 elements into vecList...
if (!vecList.empty())
{
std::cout << "List count = " << vecList.size() << std::endl;
if (vecList.empty())
{
std::cout << "List is empty" << std::endl;
}
}
my printout is:
List count = 3
List is empty
I did not do anything to "vecList" other than printing out, yet after I printed the size of the vector, the size becomes 0. How is that possible? Any advice is appreciated.
This happened when I am running my build on an Iphone environment.
Thanks
Alexander
Since both std::vector<>empty() and std::vector<>::size() are const member functions and cannot alter the vector's content, the only ways I can see to get that result is by using multiple threads or invoking Undefined Behavior.
Likely candidates are other threads modifying the vector and messing up the vector's internals by buffer overflows and the like.
This
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> vecList;
vecList.push_back(1);
vecList.push_back(2);
vecList.push_back(3);
if (!vecList.empty())
{
std::cout << "List count = " << vecList.size() << std::endl;
if (vecList.empty())
{
std::cout << "List is empty" << std::endl;
}
}
return 0;
}
prints List count = 3 for me. I bet it does the same for you. If so, then there must be something messing things up in the code you don't show.
The only way to find out what it is (other than posting the exact right snippet here and have someone guess right) is to remove all extra code step by step until the problem disappears and then look at the code that triggered it.
You might also want to try Valgrind. Allot of times use of uninitialized values, especially with system calls can cause truly weird behavior.
For instance, a common mistake is the following ( yeah I've made this mistake myself ):
struct timeval tv;
tv.tv_sec = 5;
// This is supposed to sleep for 5 seconds
select(0, NULL,NULL,NULL, &tv);
What's missing? You need to init the second member of the struct as such tv.tv_usec = 0; otherwise it can cause seemingly random errors in completely unrelated sections of the program. Valgrind can help you catch some of these things.
Try debuging your code. It is easy and you will understand when exactly it becomes empty. Though, there is nothing ideal, anyway trust such constructs like STL and other well-kown libraries. In 99.99% cases the cause of the promblem is the programmer.
Looks your code like this? Note the semicolon after the second if.
std::vector<int> vecList;
...populate 3 elements into vecList...
if (!vecList.empty())
{
std::cout << "List count = " << vecList.size() << std::endl;
if (vecList.empty());
{
std::cout << "List is empty" << std::endl;
}
}
If this actually happens, it's most probably another thread modifying the vector.