This code freezes VS2010 sp1:
// STC_14_1.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <exception>
#include <iostream>
#include <cstdlib>
using std::cerr;
using std::cout;
using std::cin;
void my_new_handler()
{
cerr << "Mem. alloc failed.";
std::exit(-1);
}
//std::unexpected_handler std::set_unexpected(std::unexpected_handler);
class STC
{
std::new_handler old;
public:
STC(std::new_handler n_h):old(std::set_new_handler(n_h))
{ }
~STC()
{
std::set_unexpected(old);
}
};
int main(int argc, char* argv[])
{
STC stc(&my_new_handler);
while (true)
{
auto tmp = new int[50000];
}
return 0;
}
Is it that I'm doing something wrong or it's VS's problem?
Your loop is endless:
while (true)
{
auto tmp = new int[50000];
}
You have to define a condition to exit outside of the loop. In counterpart, VS will be frozen iterating through the loop and draining memory from the heap (since you allocate a new block of memory in every iteration).
EDIT: Your handler is not called because it has to be defined as void __cdecl:
void __cdecl no_memory () {
cout << "Failed to allocate memory!\n";
exit (1);
}
Since handler is not called, the problem is in endless loop.
It works on my VS 2010.
When you say 'freezes', are you sure that it's not just that the code is still actually running and has not hit the new handler code yet. I tried running the example set_new_handler code from the MSDN here, and it still took a minute or so and the example is allocating 5000000 at a time rather than 50000.
Related
I am trying to play a song in a background thread of my GUI application so that the song doesn't block the GUI thread. Is there a simple way to do this with either std::thread or SFML Threads?
I have tried using std::thread for this, but it still blocks the GUI thread when I call my_thread.join().
Here is an example of what I want to do:
#include <thread>
#include <SFML/Audio.hpp>
#include <unistd.h>
#include <iostream>
void func() {
sf::Music music;
music.openFromFile("mysong.wav");
music.play();
// if I don't have usleep here the function exits immediately
// why is that exactly???
usleep(100000000);
}
int main() {
std::thread my_thread(func);
my_thread.join();
// this is where I would process events/build windows in GUI
while(1)
std::cout << "here"; // <--- Want this to run while song plays
}
in SFML you need to have a valid sf::Sound or sf::Music for music to play, when that variable gets destroyed you will no longer have a valid reference to that object a possible solution for the code you posted would be something like this:
#include <SFML/Audio.hpp>
#include <unistd.h>
#include <iostream>
class CAudio
{
sf::Music music;
public:
void func()
{
music.openFromFile("mysong.wav");
music.play();
}
sf::Status getStatus()
{
return music.getStatus();
}
}
int main() {
CAudio my_music;
my_music.func();
// http://www.sfml-dev.org/documentation/2.0/SoundSource_8hpp_source.php
while(my_music.getStatus() == sf::Status::Playing)
{
std::cout << "here"; // <--- Want this to run while song plays
}
}
Also, always use brackets, regardless if its a 1 line statement always use brackets, I know its allowed but it will make your life easier when you troubleshoot later on.
I have written very simple program and expected to crash, and it crashes. Now, I have set terminate function, but it will not be called and program just crashed without calling this function.
I have test program both inside debugger/outside debugger, built in both debug/release mode, but showing same behaviour (at least no calling my terminate function). I am musing VS 2012 and Windows 10.
void func()
{
cout<<"Aah you threw exception"<<endl;
}
int main(int argc, char* argv[])
{
set_terminate(func); //setting terminate function
int *p = NULL;
*p =11;
cout<<*p; //this will throw exception
}
C++ is not Java! A signal (or trap) can be generated by dereferencing a nullptr, but it is not automatically translated in C++ exception. On a POSIX compliant system, you can try to use the signal function to catch a signal as proposed by Throwaway Account 3 Million. On Windows, you can try to use the C structured exception handling.
If you don't, and still generate such a trap, the standard just defines that as an Undefined Behaviour, and it commonly just abort the program immediately, bypassing any set_terminate, atexit or whatever function you planned to be call on a controlled termination of your program.
Use signal to catch segmentation errors:
#include <iostream>
#include <signal.h>
using namespace std;
void func(int signal) {
cerr << "Caught signal " << signal << endl;
}
int main() {
signal(SIGSEGV, func);
void (*p)() = NULL;
p();
}
Well, I just wrote a simple logger program with log4cxx lib, It is working fine so far, but then I realized the exception handling doesnt work as I expected:
#include <iostream>
#include <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/helpers/exception.h>
using namespace std;
using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::helpers;
int main(int argc, char *argv[])
{
/* some code here ... */
try
{
DOMConfigurator::configure("/path/to/logcfg.xml");
}
catch (Exception&)
{
cout << "error: problem in reading log config file" << endl;
/* here I want to free up some objects! */
exit(EXIT_FAILURE);
}
}
So, now lets say the logcfg.xml does not exist, the program will print out this message and exit:
log4cxx: Could not open file [/wrong/path/to/logcfg.xml].
Which seems to me, it never reached my exception handler, but raised and handled in library itself. Could you please tell me what is proper way to handle such case ?
Thanks
This is really driving me crazy:
#include <iostream>
#include <vector>
#include <string.h>
#include <thread>
using namespace std;
void test() {
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
}
int main() {
thread(test).join();
return 0;
}
The code compiles fine with the -std=c++11 flag to the compiler and the -pthread flag to the linker.
BUT: Eclipse does either know the std::thread or the myvector.begin()->length(), even if the code runs fine eclipse warns me "Method 'length' could not be resolved".
I tried every possible solution in here: Eclipse CDT C++11/C++0x support without any success. This took me so many hours now, what am I doing wrong?!
Is there anybody getting a project setup without problems with this code?
EDIT: Other code example - same problem:
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
class TestClass {
public:
void test() {
cout << "test" << endl;
}
};
void test() {
vector<TestClass> testClassVector;
TestClass x;
testClassVector.push_back(x);
testClassVector.begin()->test();
}
int main() {
thread(test).join();
return 0;
}
Compiles and runs correct, but returns in eclipse: Method 'test' could not be resolved
EDIT:
working versions:
((TestClass)*(testClassVector.begin())).test();
TestClass foo2 = *(testClassVector.begin());
foo2.test();
still not working:
testClassVector.begin()->test();
The last compiles and works like the two above, but eclipse still claims:
Method 'test' could not be resolved
Maybe I'm wrong, but I think your problem don't come from Eclypse. Juste, begin() on a vector return a std::vector<T>::iterator first, this is not a pointer and there is no method length, but you can ask for the vector size with myvector.size(); if this is what you want.
The problem could come from your #include <string.h> that is not the same as #include <string>, string.h is for string operation like strcmp, strstr, etc... juste string will define the std::string object.
I don't have Eclipse set up but the problem appears to be around std::string. Does the problem go away if you remove the threading from the example? (I also changed to #include <string> instead of string.h)
#include <iostream>
#include <vector>
#include <string>
#include <thread>
using namespace std;
#if 0
void test() {
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
}
#endif
int main() {
//thread(test).join();
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
return 0;
}
That should hopefully print out 10.
Update from comment:
Does this generate the Eclipse warning?
auto tmp = *(myvector.begin());
std::cout << tmp.length() << std::endl;
What about this?
std::string foo("abc123");
std::cout << foo.length() << std::endl;
I guess one more too:
std::string foo2 = *(myvector.begin());
std::cout << foo2.length() << std::endl;
The solution found:
I downloaded eclipse kepler Kepler
Created a new project and tried to compile this source code (like above):
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
class TestClass {
public:
void test() {
cout << "test" << endl;
}
};
void test() {
vector<TestClass> testClassVector;
TestClass x;
testClassVector.push_back(x);
testClassVector.begin()->test();
}
int main() {
thread(test).join();
return 0;
}
On the first run eclipse told me, thread belongs to the new c++11 standard and I have to add -std=c++11 to the compiler flags. To use thread I also added -pthread to the linker flags. With this steps the code could be compiled, but eclipse marks the thread still as unknown. To fix this I proceeded the following step:
Under C/C++ Build (at project settings), find the Preprocessor Include Path and go to the Providers Tab. Deselect all except CDT GCC Builtin Compiler Settings. Then untag Share settings entries … . Add the option -std=c++11 to the text box called Command to get compiler specs.
Found here.
Now - unbelievable but true - it works, even without any errors marked by eclipse. The solution is using the (beta) version of eclipse, wich seems to handle this in a better way.
Thanks for all your help!
struct test_struct
{
test_struct() {}
~test_struct() {}
};
#include <vector>
#include <memory>
#include <cstdio>
int main()
{
printf("ctor begin\n");
{
std::vector<std::unique_ptr<test_struct>> test_vec;
const int count = 100000;
for (auto i = 0; i < count; i++) {
test_vec.emplace_back(new test_struct);
}
printf("dtor begin\n");
}
printf("dtor end\n");
}
I'm using VS2010, and found some ridiculous performance issue. The code above works well both in debug and release build (ctrl+f5), but when debugger is attached(f5), dtor call for unique_ptr class is intolerably slow. The result machine code is fairly optimized, so I don't expect that it's compiler issue rather than debugger's, but I don't know how to deal with it. My question is
Is this problem able to be reproduced on your machine?
What's the reason of this behaviour?
Is there any workaround?
The slowdown is caused by memory checking that occurs whenever memory is freed. However, this is a special system-/debugger-level heap, and isn't anything you can control from within your program.
There's a great article on the issue. To summarize: you have to set an environment variable to disable it!
Luckily, you can set project-specific environment variables from the Debugging options in the Project Settings for your project, so that the environment variable is only applied to your program.
I used this simplified program to test:
#include <iostream>
#include <memory>
#include <vector>
int main()
{
std::cout << "ctor begin" << std::endl;
{
std::vector<std::unique_ptr<int>> test_vec;
for (unsigned i = 0; i < 100000; i++)
test_vec.emplace_back(new int);
std::cout << "dtor begin" << std::endl;
}
std::cout << "dtor end" << std::endl;
}
By setting _NO_DEBUG_HEAP=1 as an environment variable (either system-wide, which I won't recommend, or through the Debugging options), the code runs in roughly the same amount of time irrespective of whether or not the debugger is attached.