std::thread throws Access violation exception when created with arguments? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm using VS2015 and encounter a extremely strange problem when using std::thread.
void Klass::myfunc(int a, int b) { std::cout << a << ' ' << b << std::endl; }
// ...
auto t = std::thread(&Klass::myfunc, this, 100, 200); <- runtime error after called
// ...
t.join();
It works well on Debug mode, but throws an "Access violation exception" when I turn to Release mode.
What's more, if I try to modify "myfunc" to this:
void Klass::myfunc() { std::cout << "foo" << std::endl; }
// ...
auto t = std::thread(&Klass::myfunc, this); // everything goes well
// ...
t.join();
it works well again.
I'm guarantee that "&Klass::myfunc" and "this" pointers are not NULL. And there is a "join" after several lines when the ctor is called.
I guess it might be some kind of "undefined behavior" but I have no idea what is it exactly.
The call stack is something like this:
000000c83a4ffd40() Unknown
> distributed_word_embedding.exe!std::_LaunchPad<std::unique_ptr<std::tuple<void (__cdecl multiverso::Communicator::*)(void) __ptr64,multiverso::Communicator * __ptr64>,std::default_delete<std::tuple<void (__cdecl multiverso::Communicator::*)(void) __ptr64,multiverso::Communicator * __ptr64> > > >::_Run(std::_LaunchPad<std::unique_ptr<std::tuple<void (__cdecl multiverso::Communicator::*)(void),multiverso::Communicator *>,std::default_delete<std::tuple<void (__cdecl multiverso::Communicator::*)(void),multiverso::Communicator *> > > > * _Ln) Line 247 C++
distributed_word_embedding.exe!std::_Pad::_Call_func(void * _Data) Line 210 C++
ucrtbase.dll!00007ffabdc7be1d() Unknown
kernel32.dll!00007ffabfae8102() Unknown
ntdll.dll!00007ffac26bc5b4() Unknown

You should always make sure you join (or possibly detach) a thread, otherwise leaving main especially with a thread using objects (in this case this) will (sometimes) cause problems.
//... details omitted...
int main()
{
auto t = std::thread(&Klass::myfunc, this);
t.join(); //<----- NOTE THIS
}
Anthony William's threading blog goes through this in detail. With an example very similar to your second one:
void my_thread_func()
{
std::cout<<"hello"<<std::endl;
}
int main()
{
std::thread t(my_thread_func);
}
He says
If you compile and run this little application, what happens? Does it
print hello like we wanted? Well, actually there's no telling. It
might do or it might not. I ran this simple application several times
on my machine, and the output was unreliable: sometimes it output
"hello", with a newline; sometimes it output "hello" without a
newline, and sometimes it didn't output anything. What's up with that?
Surely a simple app like this ought to behave predictably?
He then introduces the idea of using join as I did above, and says,
The problem is we're not waiting for our thread to finish. When the
execution reaches the end of main() the program is terminated,
whatever the other threads are doing.

Related

simple question about standard c++ multithreading [duplicate]

This question already has answers here:
When should I use std::thread::detach?
(6 answers)
Closed 2 years ago.
hi i am newbie learning c++ multithreading
this ques may look stupid but just curious why it's happening
would be amazing if somebody points out what is going on underhood
so,
class background_task
{
public:
void operator()() const
{
for (int i = 0; i < 1000; ++i)
std::cout << "Hello world " << i << std::endl;
}
};
void Func()
{
for(int i=0; i<1000;++i)
std::cout << "Hello world " <<i<< std::endl;
};
void main()
{
background_task bt;
std::thread t(bt);
//t.detach();
}
it gives me the runtime error saying "abort() has been called"
and with detach() it works just fine.
the either case, the new thread execute the loop all the way to end(1000times)
i just guess the error happens because there's additional thread going when runtime thread exits.
but even when i called detach(), there's still additional thread as well and output no error in this case.
i guess, in the destructor of std::thread, it checked like assert(!joinable()) or am i missing something else?
You need to either detach or join std::thread objects before they get destroyed. This is part of the API and documented in the destructor:
std::thread::~thread
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.
What you usually want is to join the thread, which blocks the current thread until the other thread has finished.
If you want a thread that automatically joins on destruction, you can use C++20's std::jthread instead.

SDL Multithreading with variables -- Doesn't work as expected [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have in a namespace called Main an static integer, and a static class variable called other, like this:
namespace Main {
void test();
static Client other;
static int v = 0;
}
Then, when the program starts, Main::test() is called, and creates a thread via SDL:
void test() {
SDL_CreateThread(Client::test, (const char*)"Client", (void*)NULL);
v = 1;
std::cout << v << std::endl;
...
}
This makes the Client start a function called test, which prints the vector size forever, like so:
int Client::test(void* data)
{
while(1) {std::cout << Main::v << std::endl; }
}
Now, here's the problem! Main returns 1 and Client returns a lot of zeros! What happened there? The variable is static, so it should be the same for Client!
std::vector.size() is, by definition, the number of elements in the vector.
Any situation where you think that isn't the case, or you see symptoms of that not being the case, you are probably experiencing undefined behavior due to memory corruption or out-of-bounds accesses.
Note that assigning to an indexed location of a vector v[n] = x; does not extend the vector, and is undefined behavior if n >= v.size().
Without explicit synchronization, the compiler is allowed to optimize the Client::test method by assuming that v never changes.
This is because it obviously doesn't change in that thread, it's your responsibility to tell the compiler if it could change in a different thread, and you did no such thing.
You are using a standard container in two threads, so you need to protect every access with a mutex. That creates a memory fence (which solves the problem you've seen), and protects from internal corruption when you perform actions on the container from different threads simultaneously (which your answer does not attempt to solve).

How Can this == nullptr Ever be true Without Invoking Undefined Behavior? [duplicate]

Does it ever make sense to check if this is null?
Say I have a class with a method; inside that method, I check this == NULL, and if it is, return an error code.
If this is null, then that means the object is deleted. Is the method even able to return anything?
Update: I forgot to mention that the method can be called from multiple threads and it may cause the object to be deleted while another thread is inside the method.
Does it ever make sense to check for this==null? I found this while doing a code review.
In standard C++, it does not, because any call on a null pointer is already undefined behavior, so any code relying on such checks is non-standard (there's no guarantee that the check will even be executed).
Note that this holds true for non-virtual functions as well.
Some implementations permit this==0, however, and consequently libraries written specifically for those implementations will sometimes use it as a hack. A good example of such a pair is VC++ and MFC - I don't recall the exact code, but I distinctly remember seeing if (this == NULL) checks in MFC source code somewhere.
It may also be there as a debugging aid, because at some point in the past this code was hit with this==0 because of a mistake in the caller, so a check was inserted to catch future instances of that. An assert would make more sense for such things, though.
If this == null then that means the object is deleted.
No, it doesn't mean that. It means that a method was called on a null pointer, or on a reference obtained from a null pointer (though obtaining such a reference is already U.B.). This has nothing to do with delete, and does not require any objects of this type to have ever existed.
Your note about threads is worrisome. I'm pretty sure you have a race condition that can lead to a crash. If a thread deletes an object and zeros the pointer, another thread could make a call through that pointer between those two operations, leading to this being non-null and also not valid, resulting in a crash. Similarly, if a thread calls a method while another thread is in the middle of creating the object, you may also get a crash.
Short answer, you really need to use a mutex or something to synchonize access to this variable. You need to ensure that this is never null or you're going to have problems.
I know that this is old but I feel like now that we're dealing with C++11-17 somebody should mention lambdas. If you capture this into a lambda that is going to be called asynchronously at a later point in time, it is possible that your "this" object gets destroyed before that lambda is invoked.
i.e passing it as a callback to some time-expensive function that is run from a separate thread or just asynchronously in general
EDIT: Just to be clear, the question was "Does it ever make sense to check if this is null" I am merely offering a scenario where it does make sense that might become more prevalent with the wider use of modern C++.
Contrived example:
This code is completely runable. To see unsafe behavior just comment out the call to safe behavior and uncomment the unsafe behavior call.
#include <memory>
#include <functional>
#include <iostream>
#include <future>
class SomeAPI
{
public:
SomeAPI() = default;
void DoWork(std::function<void(int)> cb)
{
DoAsync(cb);
}
private:
void DoAsync(std::function<void(int)> cb)
{
std::cout << "SomeAPI about to do async work\n";
m_future = std::async(std::launch::async, [](auto cb)
{
std::cout << "Async thread sleeping 10 seconds (Doing work).\n";
std::this_thread::sleep_for(std::chrono::seconds{ 10 });
// Do a bunch of work and set a status indicating success or failure.
// Assume 0 is success.
int status = 0;
std::cout << "Executing callback.\n";
cb(status);
std::cout << "Callback Executed.\n";
}, cb);
};
std::future<void> m_future;
};
class SomeOtherClass
{
public:
void SetSuccess(int success) { m_success = success; }
private:
bool m_success = false;
};
class SomeClass : public std::enable_shared_from_this<SomeClass>
{
public:
SomeClass(SomeAPI* api)
: m_api(api)
{
}
void DoWorkUnsafe()
{
std::cout << "DoWorkUnsafe about to pass callback to async executer.\n";
// Call DoWork on the API.
// DoWork takes some time.
// When DoWork is finished, it calls the callback that we sent in.
m_api->DoWork([this](int status)
{
// Undefined behavior
m_value = 17;
// Crash
m_data->SetSuccess(true);
ReportSuccess();
});
}
void DoWorkSafe()
{
// Create a weak point from a shared pointer to this.
std::weak_ptr<SomeClass> this_ = shared_from_this();
std::cout << "DoWorkSafe about to pass callback to async executer.\n";
// Capture the weak pointer.
m_api->DoWork([this_](int status)
{
// Test the weak pointer.
if (auto sp = this_.lock())
{
std::cout << "Async work finished.\n";
// If its good, then we are still alive and safe to execute on this.
sp->m_value = 17;
sp->m_data->SetSuccess(true);
sp->ReportSuccess();
}
});
}
private:
void ReportSuccess()
{
// Tell everyone who cares that a thing has succeeded.
};
SomeAPI* m_api;
std::shared_ptr<SomeOtherClass> m_data = std::shared_ptr<SomeOtherClass>();
int m_value;
};
int main()
{
std::shared_ptr<SomeAPI> api = std::make_shared<SomeAPI>();
std::shared_ptr<SomeClass> someClass = std::make_shared<SomeClass>(api.get());
someClass->DoWorkSafe();
// Comment out the above line and uncomment the below line
// to see the unsafe behavior.
//someClass->DoWorkUnsafe();
std::cout << "Deleting someClass\n";
someClass.reset();
std::cout << "Main thread sleeping for 20 seconds.\n";
std::this_thread::sleep_for(std::chrono::seconds{ 20 });
return 0;
}
FWIW, I have used debugging checks for (this != NULL) in assertions before which have helped catch defective code. Not that the code would have necessarily gotten too far with out a crash, but on small embedded systems that don't have memory protection, the assertions actually helped.
On systems with memory protection, the OS will generally hit an access violation if called with a NULL this pointer, so there's less value in asserting this != NULL. However, see Pavel's comment for why it's not necessarily worthless on even protected systems.
Your method will most likely (may vary between compilers) be able to run and also be able to return a value. As long as it does not access any instance variables. If it tries this it will crash.
As others pointed out you can not use this test to see if an object has been deleted. Even if you could, it would not work, because the object may be deleted by another thread just after the test but before you execute the next line after the test. Use Thread synchronization instead.
If this is null there is a bug in your program, most likely in the design of your program.
I'd also add that it's usually better to avoid null or NULL. I think the standard is changing yet again here but for now 0 is really what you want to check for to be absolutely sure you're getting what you want.
This is just a pointer passed as the first argument to a function (which is exactly what makes it a method). So long as you're not talking about virtual methods and/or virtual inheritance, then yes, you can find yourself executing an instance method, with a null instance. As others said, you almost certainly won't get very far with that execution before problems arise, but robust coding should probably check for that situation, with an assert. At least, it makes sense when you suspect it could be occuring for some reason, but need to track down exactly which class / call stack it's occurring in.
I know this is a old question, however I thought I will share my experience with use of Lambda capture
#include <iostream>
#include <memory>
using std::unique_ptr;
using std::make_unique;
using std::cout;
using std::endl;
class foo {
public:
foo(int no) : no_(no) {
}
template <typename Lambda>
void lambda_func(Lambda&& l) {
cout << "No is " << no_ << endl;
l();
}
private:
int no_;
};
int main() {
auto f = std::make_unique<foo>(10);
f->lambda_func([f = std::move(f)] () mutable {
cout << "lambda ==> " << endl;
cout << "lambda <== " << endl;
});
return 0;
}
This code segment faults
$ g++ -std=c++14 uniqueptr.cpp
$ ./a.out
Segmentation fault (core dumped)
If I remove the std::cout statement from lambda_func The code runs to completion.
It seems like, this statement f->lambda_func([f = std::move(f)] () mutable { processes lambda captures before member function is invoked.

C++, Qt4 - QLabel.setText() seemingly causes segmentation fault

EDIT: PROBLEM SOLVED, see my answer. TL;DR: wasn't related to Qt, I made a stupid mistake with array (std::vector) ranges.
Using Windows7, Qt version 4.8.7, x86_64-w64-mingw32-g++ as compiler, Cygwin for compiling, Notepad++ for editing. (The same project has Flex and Bisonc++ in it as well, but those are not related to the issue and work fine.)
I have an std::vector< QLabel* >, and I attempt to fill it with data. In one test case (which is the QFrame containing the vector getting the data from the main function with no involvement from other classes) this works out fine, as expected.
In another case, when using a QMainWindow to trigger it's own slot-method which calls for the same function, it runs into a segmentation fault at the QLabel.setText( QString::number() ) part.
ui_parts.h
#ifndef UI_PARTS_H_INCLUDED
#define UI_PARTS_H_INCLUDED
#include <QWidget>
#include <QLabel>
#include <QGridLayout>
#include <QFrame>
#include <vector>
#include <string>
class regDisplay : public QFrame{
Q_OBJECT
public:
regDisplay(int _meret, const std::string &nev, QWidget *parent = 0);
~regDisplay() {}; // not actually in the header, here for compression
int size() const { return meret; };
void setValues(const std::vector<AP_UC> &val);
private:
QGridLayout* gridLayout;
int meret;
std::vector<unsigned char> valueVec;
std::vector<QLabel*> valueLabel;
};
#endif // UI_PARTS_H_INCLUDED
ui_parts.cpp
#include <iostream>
#include "ui_parts.h"
using namespace std;
regDisplay::regDisplay(int _meret, const std::string &nev, QWidget *parent)
: QFrame(parent), name(nev), meret(_meret){
valueVec.resize(meret, 0);
valueLabel.resize(meret, NULL);
gridLayout = new QGridLayout(this);
// [...] setting up other properties of the widget
for (int i = 0; i < meret; ++i){
valueLabel[i] = new QLabel(this);
// [...] set properties for valueLabel[i]
gridLayout -> addWidget( valueLabel[i], 1, i);
}
}
// the following function which is suspected with causing the segfault
void regDisplay::setValues(const std::vector<AP_UC> &val){
for (int i = 0; i < meret; ++i)
{
valueVec[i] = val[i];
cout << (int)valueVec[i] << "\t" << (QString::number( (int)valueVec[i] )).toStdString() << endl;
cout << "ptr: " << (valueLabel[i]) << endl;
if ( valueLabel[i] == NULL ){
cout << "NULL POINTER? WTF " << i << endl;
} else{
cout << "not null pointer " << i << endl;
}
cout << "kek" << endl;
valueLabel[i] -> setText( QString::number( (int)valueVec[i] )); // SEGFAULT
cout << i << "+" << endl;
}
}
Calling the function:
vector<unsigned char> vecUC(4);
allapot.get_reg("eax", vecUC); // I'm 100% sure this works correctly, tested thoroughly
// it makes vecUC equal to an std::vector<unsigned char> which is 4 long
eax -> setValues( vecUC ); // regDisplay* eax;
// initialized: eax = new regDisplay(4, "eax", this ); in the constructor of this class (which inherits from QMainWindow)
Console output of this piece of code:
0 0
ptr: 0x32f160
not null pointer 0
kek
Segmentation fault
My read on this:
valueVec[i] and its QString version are both 0 (the argument of setText() seems to be fine)
valueLabel[i] has a pointer value which isn't 0, initialized as such in the constructor
valueLabel[i] is not a nullpointer (i == 0 in this case)
the first cout before the setText() works, the second does not
Removing (commenting) the setText() calls from throughout the code make it work properly (but I need some way of putting out text on the UI, so they're needed in some form for the purpose of the program).
'make ui_vec' creates the testing module for the regDisplay and veremDisplay classes, which works fine
'make ui_main' creates the testing module for mainDisplay, which causes the issues to arise
I do not know what causes the issue and I'd appreciate any help with removing it. Thank you in advance.
Update (16.05.14):
I recreated the entire project in wxWidgets, and it worked fairly similarly, but at basically the same point it also started throwing segfaults around. It appears to happen randomly, sometimes the entire program works correctly, sometimes on the first action it fails.
However, running the program through gdb completely solved the issue, I haven't encountered any segfaults.
Update (16.05.16):
After some further testing, it appears that the problem is somewhere in the bisonc++ / flex parser I created. There is one piece of code using it that works completely fine every time, and if I try to add to it (going back with an std::stack to previous states; using a class to navigate) it segfaults after the second instruction (the first works fine).
Footnotes:
Link for repository - the problem is in src/cpp/ui_parts.cpp line79 (regDisplay::setValues()), called from mainDisplay::displayAllapot() (src/cpp/ui_main.cpp line195). Debug messages might have changed a bit, rest of the code is the same.
Most of the documentation and commments are in Hungarian and not in English, my apologies for that.
Another (probably related issue): the very same program sometimes runs into the same segmentation fault at different locations - sometimes the regDisplay::setValues() works fine, and the problem appears at veremDisplay::updateValues() - during a loop, maybe on the first run, maybe later, sometimes it works through the entire thing, and I haven't seen any consistency in it yet (it mostly stops working on the first run).
Third problem (again, most likely related): when calling the openFile() function, it runs properly until the end (the last instruction being a debug message and working correctly), but gives a seg-fault (this would make me think of destructor issues). However, if I connect a different function (oF2()) to the same event instead, then have oF2() call openFile() and write a debug message (and to nothing else), then the debug message shows and the segmentation fault appears afterward - and there were no local variables or parameters received, so no destructor should run between the last instruction of the code and the function terminating.
I found the issue, I went up to 10 in an std::vector that was only 7 in size (it only appeared in some test cases), fixing that solved every issue I had, no segmentation faults appeared so far in fairly extensive testing.
Since the real problem wasn't related to Qt in any way (also not to bisonc++ or flex), apart from the "check your array ranges" lesson, I don't think there is any real reason to keep this thread around. If mods see this, feel free to delete the question - if the solution isn't enough to keep it up.
I don't see in your code problem that may cause segfault.
But my guess that your compilation flags may cause such segfault.
For example, you use std::string and toStdString.
If Qt compiled with another version of compiler, or for example if you link you program statically with c++ runtime library (which you do accroding to your makefile[-static-libgcc -static-libstdc++]) and Qt links with dll variant of c++ runtime, then your program and Qt library may think that they work with the same version of std::string, but actually the work wtih different versions of std::string,
and std::string that allocated inside Qt may cause segfault, when you call
destructor of it inside your program. Or you create QFile with FILE * created by fopen, and you catch segfault in ~QFile, because of Qt FILE and your FILE are different.
So make sure, that your Qt compiled with the same compiler as your program,
and Qt builds with the same flags as your program.
Actually sizeof(std::string) and sizeof(FILE) may be the same, but can be used different allocators.

Try/catch whole program [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've taken the habit to construct my C++ projects as follows :
int main(int ac, char* av[])
{
try
{
Object foo;
foo.run()
/* ... */
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
catch (...)
{
std::cerr << "Unknown error." << std::endl;
return 1;
}
return 0;
}
I wonder if this is a good practice, or is it better to use try/catch blocks on small pieces of codes that are "expected" to produce errors ?
Generally, catching all exceptions is not a good idea: you want to catch only these exceptions that your particular piece of code is ready to handle in a meaningful way.
However, the top-level entry point is an exception from this rule: it is a common practice to catch all exceptions yourself if you wish to control how exceptions are processed on the top level.
A common way of implementing it, however, is to write a single function that looks like main, but has a different name:
int entryPoint(int argc, char *argv[]) {
... // The real logic goes here
Object foo;
foo.run()
/* ... */
}
Your code looks like this, and never changes:
int main(int ac, char* av[])
{
try
{
return entryPoint(ac, av);
}
catch (const std::exception& e)
{
std::cout << e.what() << std::cerr;
}
catch (...)
{
std::cout << "Unknown error." << std::endl;
}
}
You can put your whole program into such a top-level exception-handler, if you want to control how unhandled exceptions are handled (if they reach top-level).
There is a dis-advantage to that though: The standard crash-behavior is pre-empted, which probably means you get no crash-dumps, and thus are missing crucial information for post-mortem debugging.
Also, they might not reach top-level, but result in std::unexpected() and by that std::terminate() being called.
Thus, you might be better served by std::set_terminate even if you want to do your own thing.
Consider doing your own thing and then crashing like normal (Which you cannot do with your global exception-handler).
The advantage is your program never crashing (on Linux it can crash tough, since signals can't be caught as exceptions)
But there is one disadvantage I can think of: When you debug your code and have a run time error, you don't know where it was or see the stack. since your program continue running from the catch. so instead of check immediately what happened you need to run again and hope you'll have the same behavior.
Another thing: if your program is Multi-threaded, it won't help to caught all exceptions, since each thread need to catch his own exceptions.
It's certainly better to try/catch as near the throw as possible if you can do something to recover from the error. Catching every fatal error on the other hand may clutter your code quite a bit.
If a throw is not caught, std::terminate will be called and you can set that function to a custom one with std::set_terminate. Inside the terminate function, you can do throw; which rethrows the uncaught object and then catch it. You must use catch(...) at the end in this case, since throwing from the terminate function is not a good thing.
Yes surely it would make difference...Let's see how.
try
{
// code which could throw an exception
}
catch(Myexception& e) //derived from std::exception
{
//do something.
}
//..some more code. //Point_1
Let's say I just want to do some manipulation after catching Myexception then then resume this function. After catching the exception code would come to POINT_1. Had I encapsulated this in try/catch it would have been ignored.