std::locale(const char*) freezes ... sometimes. Visual Studio bug? - c++

Consider the following code:
#include <sstream>
#include <iostream>
int main()
{
std::stringstream ss;
//auto loc = std::locale("de-DE"); // A
auto loc = std::locale(""); // B
ss.imbue(loc);
ss << 1.01;
std::cout << "standard formatting: " << 1.01 << std::endl;
std::cout << "localized formatting: " << ss.str() << std::endl;
}
Now, this works as expected or it freezes in line B. When using line A it is the same but I think that changing from A to B or vice versa leads to a higher chance that it works. It even happened that it worked one time and starting it again it freezes in line A or B respectively.
It is important that all this happens only when I start debugging from within VS 2015. When I execute this program from console it never freezes (release or debug doesn't matter).
So is this a Visual Studio bug?

Related

VS code set up for c++

I am new in VS code. I wrote a C++ code like one below. but unfortunately in the terminal or output panel I cannot get both of the string and variable value. in the terminal only variable's inputted value is showing. How to fix this?
#include <bits/stdc++.h>
int main()
{
int slices;
std::cin >> slices;
std::cout << "You got " << slices << " of pizzas" << std::endl;
return 0;
}

Why does the function find of C++ stl string sometimes go wrong sometime go right?

I am trying to do some file reading with C++ in Ubuntu 16.04 (GCC&G++ 5.4 and CMake 3.5.1).
The test file (named 123.txt) have only a line words just like this:
Reprojection error: avg = 0.110258 max = 0.491361
I just want to get the avg error and max error. My method is to get a line and put them into a std::string
and use string::find. My codes are very easy just like this:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
FILE *fp = fopen("123.txt", "r");
char tmp[60];
string str;
fgets(tmp, size_t(tmp), fp);
fclose(fp);
cout << tmp << endl;
str = tmp;
cout << str.size() << endl;
size_t avg = str.find("avg");
size_t max = str.find("max");
cout << avg << endl;
cout << max << endl;
}
I can use g++ to compile it successfully. But I meet a strange issue.
When I first run it in the command, it will get the right result:
Reprojection error: avg = 0.110258 max = 0.491361
52
20
37
If I run codes again, it will go wrong sometimes just like this:
p
2
18446744073709551615
18446744073709551615
The "p" is a disorderly code which can not be shown correctly in the command. I am not good at C++ and feel confused about it. Is there someone who can say something? Thank you!
The expression
fgets(tmp, size_t(tmp), fp);
is ill-formed, size_t(tmp) will not work as you expect, you need sizeof(tmp).
The 52 value you get is because fgets consumes the \n character and this is counted too, actually the string has 51 characters counting with spaces.
That said, in this case you can use better C++ tools to replace the C ones you are using, fopen can be replaced by using the fstream library, fgets can be replaced by getline.
Something like:
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream fp("123.txt"); //C++ filestream
if (fp.is_open()) {//check for file opening errors
std::string str;
std::getline(fp, str); //C++ read from file
fp.close();
std::cout << str << std::endl;
std::cout << str.size() << std::endl;
size_t avg = str.find("avg");
size_t max = str.find("max");
std::cout << avg << std::endl;
std::cout << max << std::endl;
}
else{
std::cerr << "Couldn't open file";
}
}
Note that I dind't use using namespace std;, this is for a reason, it's not a good practice, you can check this thread for more details.

weak_ptr reset affects shared_ptr?

I'm not very used to using weak_ptr and I'm facing a quite confusing situation. I'm using Intel XE 2019 Composer update 5 (package 2019.5.281) in combinaison with Visual Studio 2019 ver. 16.2.5. I compile in 64-bit. I use the standard C++ 17.
Here is the code for my spike solution:
#include <memory>
#include <iostream>
using namespace std;
int main( int argc, char* argv[] )
{
shared_ptr<int> sp = make_shared<int>( 42 );
cout << "*sp = " << *sp << endl;
weak_ptr<int> wp = sp;
cout << "*sp = " << *sp << ", *wp = " << *wp.lock() << endl;
wp.reset();
cout << "*sp = " << *sp << endl;
return 0;
}
The output I expected to have is:
*sp = 42
*sp = 42, *wp = 42
*sp = 42
...but here is what I obtained:
*sp = 42
*sp = 42, *wp = 42
*sp = -572662307
What is goin on? Is it normal for the shared_ptr to be modified/invalidated when the/an associated weak_ptr is reset? I'm a little confused about the results I obtained. To say the truth I didn't expect this result...
EDIT 1
While the bug occurs in 64-bit configuration, it doesn't in 32-bit. In this later configuration, the result is what is expected.
EDIT 2
The bug occurs only in Debug. When I build in Release, I get the expected result.
It appears it is a real bug on Intel ICC side; I have reported it.
Thanks again for helping me to pin-point this problem.
It looks like a bug in debug library, with sentinel values.It's easy to check, by using line I mentioned:
int i = 1; cout << i << " " << ++i << endl;
If output is 2 2 instead of 1 2, then compiler is not compliant and possibly still considers such case an UB. Sentinel values may be used erroneously in this case with call of reset(). Similar thing happens with deleting object created by placement new within preallocated static buffer, in debug mode it gets overwritten by some implementations with sentinel values.

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.