Boost::thread mutex issue: Try to lock, access violation - c++

I am currently learning how to multithread with c++, and for that im using boost::thread.
I'm using it for a simple gameengine, running three threads.
Two of the threads are reading and writing to the same variables, which are stored inside something i call PrimitiveObjects, basicly balls, plates, boxes etc.
But i cant really get it to work, i think the problem is that the two threads are trying to access the same memorylocation at the same time, i have tried to avoid this using mutex locks, but for now im having no luck, this works some times, but if i spam it, i end up with this exception:
First-chance exception at 0x00cbfef9 in TTTTT.exe: 0xC0000005: Access violation reading location 0xdddddded.
Unhandled exception at 0x77d315de in TTTTT.exe: 0xC0000005: Access violation reading location 0xdddddded.
These are the functions inside the object that im using for this, and the debugger is also blaming them for the exception.
int PrimitiveObj::setPos(glm::vec3 in){
boost::try_mutex::scoped_try_lock lock(myMutex);
if ( lock)
{
position = in;
return 1;
}
return 0;
}
glm::vec3 PrimitiveObj::getPos(){
boost::try_mutex::scoped_try_lock lock(myMutex);
if ( lock)
{
glm::vec3 curPos = position;
return curPos;
}
return glm::vec3(0,0,0);
}
This is the function im using to generate each primitiveobj. (updated)
void generatePrimitive(){
PrimitiveObj *obj = new PrimitiveObj();
obj->generate();
obj->setPos(getPlayerPos()+getEye()*4.0f);
prims.push_back(std::shared_ptr<PrimitiveObj>(obj));
}
Any ideas?
Edit: New functions(2), and myMutex is now private to the object. Added the function i use to generate the primitiveobjects.
Edit:
This is the code that the stack is pointing at, and this is running inside the physics thread:
nr = getNumberOfPrimitives();
double currentTime = glfwGetTime();
float deltaTime = float(currentTime - lastTime);
for(int r = 0; r < nr; r++) {
prop = getPrimitive(r);
glm::vec3 pos = prop->getPos()+glm::vec3(0,1.0f*Meter/deltaTime,0);
prop->setPos(pos);
}
Other relevant code:
int getNumberOfPrimitives(){
return prims.size();
}
PrimitiveObj * getPrimitive(int input) {
return prims[input];
}

The first idea is that your PrimitiveObj that you are calling is uninitialized, something like this:
PrimitiveObj* myObject;
myObject->getPos();
The exception you have is most likely you accessing an uninitialized pointer variable (set to 0xdddddddd so the developer recognizes it as uninitialized) and accessing a member on it that is offset by 0x10 (=16) bytes.
Access Exceptions can also happen if you access objects such as std:vector while reading and writing from different threads to the same object at the same time, but the location is often a more random looking number that starts with zeros and is divisible by 4 (e.g. 0x004da358).
Why is that the case? Debug code often initializes memory with some recognizable yet random numbers (0xdddddddd, 0xbaadfood, 0xfefefefe, etc). They are random because if the variables would always be the same, e.g. always initialized to 0, which could cause the developer to miss the fact that some variables are not initialized and the code would stop working in release. They are easy to recognize so we can tell at a glance that the number comes from uninitialized memory.
Formerly valid pointers point to the heap address space, which usually starts from a somewhat low number and counts up. If multiple objects are allocated on the heap, in normal operation each object is aligned, on a memory address divisible by 4, 8, 16, etc. the members of an object are aligned on 4 byte boundaries as well, that's why access violations caused by accessing formerly valid memory are often on addresses that start with zeros and are divisible by 4.
Keep in mind that these are rules of thumb which can and should be used to point you in the right direction, but they are not hard and fast rules. Also, they refer to debug environments. Release environments have very different rules to guessing which Access Violation is caused by what.

Related

Acces Violation 0xCCCCCCCC [duplicate]

For the past 2 days I've been stuck on a violation which I can't seem to get to go away.
I've used break points and located where the error is, but I'm just hoping one of you will know what the issue is without me having to copy+paste all my code -.-
I'm getting
First-chance exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Unhandled exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Now, a quick google search makes me think there's something peculiar going on. All the search results talk about pointers not actually pointing anywhere (0xccccccccc is a low memory address?).
I'm yet to use pointers in my code but either way I'll paste the function and point out the line the exception gets thrown (in bold):
void mMap::fillMap(){
for(int i = 0; i <= 9; i++){
for(int z = 0; z <= 19; z++){
Tile t1; // default Tile Type = "NULLTILE"
myMap[i][z] = t1;
}
}
}
Now myMap is a 2d array of type Tile. I had this working a couple of days ago until I added some other classes and it all stopped working!
Either an uninitialized pointer, or a pointer stored in memory that's been freed. I think cccccccc is the first and cdcdcdcd is the second, but it varies with compiler/library implementation.
For your particular code, probably myMap hasn't been allocated yet, then myMap[0][0] would result in an access attempt to 0xcccccccc.
It can also happen that myMap is the beginning of your class, and the class pointer was uninitialized:
class mMap
{
Tile myMap[10][20];
public:
void f() { myMap[0][0] = 0; }
};
mMap* what;
what->f(); // what is an invalid pointer
This happens because the member function is not virtual, so the compiler knows what code to run and passes the object pointer as a hidden parameter. Eventually the compiler emits a calculation like:
this + offsetof(Whatever::myMap) + z * sizeof(myMap[0]) + i * sizeof(myMap[0][0])
this, being uninitialized, is 0xcccccccc. Evidently the offsetof part is zero, and i and z are both zero the first time through your loop, so you get 0xcccccccc + 0 + 0 + 0 as the memory address.
To debug this, use the call stack and find the function that called fillMap. Then check in that function where the pointers used for member access (->) came from.
On MSVC++ and in debug mode, the debugging memory allocator sets all returned memory to 0xcccccccc, as a way to find cases of undefined behavior. In all likelihood, you never initialized myMap , or some of the pointers inside of myMap. Check your initialization code for bugs.
For all of the answers and comments happening in this question, here are good references about memory fills in Visual C++:
http://msdn.microsoft.com/en-us/library/bebs9zyz.aspx
When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?
Had similar error when I tried to fill string value in table element of my own-class type with for-loop. I declared 1000 elements in that table, so I've put something like that:
for (int i = 0; i <= 1000; i++)
{
TAble[i].name = "Some Guy";
TAble[i].age = 4;
}
Unfortunately as with string it occurred that I'm perhaps insisting on fillinf element that doesn't exist witch is element number 1000 in table. I managed to solve this by changing loop header, deleting equal sign before 1000.
Try to see whether you're not trying to call something that doesnt exist.

C++ Error :Unhandled exception : Access violation reading location [duplicate]

For the past 2 days I've been stuck on a violation which I can't seem to get to go away.
I've used break points and located where the error is, but I'm just hoping one of you will know what the issue is without me having to copy+paste all my code -.-
I'm getting
First-chance exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Unhandled exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Now, a quick google search makes me think there's something peculiar going on. All the search results talk about pointers not actually pointing anywhere (0xccccccccc is a low memory address?).
I'm yet to use pointers in my code but either way I'll paste the function and point out the line the exception gets thrown (in bold):
void mMap::fillMap(){
for(int i = 0; i <= 9; i++){
for(int z = 0; z <= 19; z++){
Tile t1; // default Tile Type = "NULLTILE"
myMap[i][z] = t1;
}
}
}
Now myMap is a 2d array of type Tile. I had this working a couple of days ago until I added some other classes and it all stopped working!
Either an uninitialized pointer, or a pointer stored in memory that's been freed. I think cccccccc is the first and cdcdcdcd is the second, but it varies with compiler/library implementation.
For your particular code, probably myMap hasn't been allocated yet, then myMap[0][0] would result in an access attempt to 0xcccccccc.
It can also happen that myMap is the beginning of your class, and the class pointer was uninitialized:
class mMap
{
Tile myMap[10][20];
public:
void f() { myMap[0][0] = 0; }
};
mMap* what;
what->f(); // what is an invalid pointer
This happens because the member function is not virtual, so the compiler knows what code to run and passes the object pointer as a hidden parameter. Eventually the compiler emits a calculation like:
this + offsetof(Whatever::myMap) + z * sizeof(myMap[0]) + i * sizeof(myMap[0][0])
this, being uninitialized, is 0xcccccccc. Evidently the offsetof part is zero, and i and z are both zero the first time through your loop, so you get 0xcccccccc + 0 + 0 + 0 as the memory address.
To debug this, use the call stack and find the function that called fillMap. Then check in that function where the pointers used for member access (->) came from.
On MSVC++ and in debug mode, the debugging memory allocator sets all returned memory to 0xcccccccc, as a way to find cases of undefined behavior. In all likelihood, you never initialized myMap , or some of the pointers inside of myMap. Check your initialization code for bugs.
For all of the answers and comments happening in this question, here are good references about memory fills in Visual C++:
http://msdn.microsoft.com/en-us/library/bebs9zyz.aspx
When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?
Had similar error when I tried to fill string value in table element of my own-class type with for-loop. I declared 1000 elements in that table, so I've put something like that:
for (int i = 0; i <= 1000; i++)
{
TAble[i].name = "Some Guy";
TAble[i].age = 4;
}
Unfortunately as with string it occurred that I'm perhaps insisting on fillinf element that doesn't exist witch is element number 1000 in table. I managed to solve this by changing loop header, deleting equal sign before 1000.
Try to see whether you're not trying to call something that doesnt exist.

Can the cause of SIGSEGV be the low ram of the system?

My system ram is small, 1.5GB. I have a C++ programm that calls a specific method about 300 times. This method uses 2 maps (they are cleared every time) and I would like to know if it is possible in some of the calls of this method that the stack is overflowed and the program fails. If I put small data (so the method is called 30 times) the program runs fine. But now it raises SIGSEGV error. I am trying to fix this for about 3 days and no luck, every solution I tried failed.
I found some cause of the SIGSEGV below but nothing helped
What is SIGSEGV run time error in C++?
Ok, here is the code.
I have 2 instances, which contain some keywords-features and their scores
I want to get their eucleidian distance, which means I have to save all the keywords for each of the instances, then find the diffs for the keywords of the first one with those of the second and then find the diffs for the remaining of the second instance. What I want is while iterating the first map, to be able to delete elements from the second. The following method is called multiple times as we have two message collections, and every message from the first one is compared with every message from the second.
I have this code but it suddenly stops although I checked it is working for some seconds with multiple cout I put in some places
Note that this is for a university task so I cannot use boost and all those tricks. But I would like to know the way to bypass the problem I am into.
float KNNClassifier::distance(const Instance& inst1, const Instance& inst2) {
map<string,unsigned> feat1;
map<string,unsigned> feat2;
for (unsigned i=0; i<inst1.getNumberOfFeatures(); i++) {
feat1[inst1.getFeature(i)]=i;
}
for (unsigned i=0; i<inst2.getNumberOfFeatures(); i++) {
feat2[inst2.getFeature(i)]=i;
}
float dist=0;
map<string,unsigned>::iterator it;
for (it=feat1.begin(); it!=feat1.end(); it++) {
if (feat2.find(it->first)!=feat2.end()) {//if and only if it exists in inst2
dist+=pow( (double) inst1.getScore(it->second) - inst2.getScore(feat2[it->first]) , 2.0);
feat2.erase(it->first);
}
else {
dist+=pow( (double) inst1.getScore(it->second) , 2.0);
}
}
for (it=feat2.begin(); it!=feat2.end(); it++) {//for the remaining words
dist+=pow( (double) inst2.getScore(it->second) , 2.0);
}
feat1.clear(); feat2.clear(); //ka8arizoume ta map gia thn epomenh xrhsh
return sqrt(dist);
}
and I also tried this idea in order to not have to delete something but it suddenly stops too.
float KNNClassifier::distance(const Instance& inst1, const Instance& inst2) {
map<string,unsigned> feat1;
map<string,unsigned> feat2;
map<string,bool> exists;
for (unsigned i=0; i<inst1.getNumberOfFeatures(); i++) {
feat1[inst1.getFeature(i)]=i;
}
for (unsigned i=0; i<inst2.getNumberOfFeatures(); i++) {
feat2[inst2.getFeature(i)]=i;
exists[inst2.getFeature(i)]=false;
if (feat1.find(inst2.getFeature(i))!=feat1.end()) {
exists[inst2.getFeature(i)]=true;
}
}
float dist=0;
map<string,unsigned>::iterator it;
for (it=feat1.begin(); it!=feat1.end(); it++) {
if (feat2.find(it->first)!=feat2.end()) {
dist+=pow( (double) inst1.getScore(it->second) - inst2.getScore(feat2[it->first]) , 2.0);
}
else {
dist+=pow( (double) inst1.getScore(it->second) , 2.0);
}
}
for (it=feat2.begin(); it!=feat2.end(); it++) {
if(it->second==false){//if it is true, it means the diff was done in the previous iteration
dist+=pow( (double) inst2.getScore(it->second) , 2.0);
}
}
feat1.clear(); feat2.clear(); exists.clear();
return sqrt(dist);
}
If malloc fails and thus returns NULL it can indeed lead to a SIGSEGV assuming the program does not properly handle that failure. However, if memory was that low your system would more likely start killing processes using lots of memory (the actual logic is more complicated, google for "oom killer" if you are interested).
Chances are good that there's simply a bug in your program. A good way to figure this out is using a memory debugger such as valgrind to see if you access invalid memory locations.
One possible explanation is that your program accesses a dynamically-allocated object after freeing it. If the object is small enough, the memory allocator keeps the memory around for the next allocation, and the access after free is harmless. If the object is large, the memory allocator unmaps the pages used to hold the object, and the access after free causes a SIGSEGV.
It is virtually certain that regardless of the underlying mechanism by which the SIGSEGV occurs, there is a bug in the code somewhere that is a key part of the causal chain.
As mentioned above, the most probable cause is bad memory allocation or memory leak. Check for buffer overflows, or if you try to access a resource after you free it.
1.5GB isn't that small. You can do a lot in 1.5GB in general. For 300 iterations to use up 1.5GB (let's say 0.5GB is used by the OS kernel, etc), you need to use roughly 32MB per iteration. That is quite a lot of memory, so, my guess is that either your code is actually using A LOT of memory, or your code contains a leak of some sort. More likely the latter. I have worked on machines with less than 64KB, and my first PC had 8MB of ram, and that was considered A LOT at the time.
No, this code is unable to cause a segfault if the system runs out of memory. map allocation uses the new operator, which does not use the stack for allocation. It uses the heap, and will throw a bad_alloc exception if the memory is exhausted, aborting before an invalid memory access can happen:
$ cat crazyalloc.cc
int main(void)
{
while(1) {
new int[100000000];
}
return 0;
}
$ ./crazyalloc
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
The fact that an alternative implementation also crashes is a hint that the problem is not in this code.
The problem is on the Instance class instead. It's probably not lack of memory, it should be a buffer overflow, which can be confirmed with a debugger.

Difficult to track SIGSEGV Segmentation fault in large program

I apologise for posting a question that has been asked many times (I've just read 10 pages of them) but I can't find a solution.
I'm working on a multi-threaded graphic/audio program using OpenGL and Portaudio respectively. The audio thread uses a library I'm making for audio processing objects. The SIGSEGV happens maybe 20% of the time (much less when debugging) and happens when resetting loads of audio objects with new stream information (sample rate, vector size etc). Code::blocks Debugger states the fault as originating from different places each time the fault happens.
This is the audio processing loop:
while(true){
stream->tick();
menuAudio.tick();
{
boost::mutex::scoped_lock lock(*mutex);
if(channel->AuSwitch.resetAudio){
uStreamInfo newStream(channel->AuSwitch.newSrate,
channel->AuSwitch.newVSize, channel->AuSwitch.newChans);
menuAudio.resetStream(&newStream);
(*stream) = newStream;
menuAudio.resetStream(stream);
channel->AuSwitch.resetAudio = false;
}
}
}
It checks information from the graphics thread telling it to reset the audio and runs the resetStream function of the patch object, which is basically a vector for audio objects and runs each of them:
void uPatch::resetStream(uStreamInfo* newStream)
{
for(unsigned i = 0; i < numObjects; ++i){
/*This is where it reports this error: Program received signal SIGSEGV,
Segmentation fault. Variables: i = 38, numObjects = 43 */
objects[i]->resetStream(newStream);
}
}
Sometimes it states the SIGSEGV as originating from different locations, but due to the rarity of it faulting when run with the debugger this is the only one I could get to happen.
As there are so many objects, I won't post all of their reset code, but as an example:
void uSamplerBuffer::resetStream(uStreamInfo* newStream)
{
audio.set(newStream, false);
control.set(newStream, true);
stream = newStream;
incr = (double)buffer->sampleRate / (double)stream->sampleRate;
index = 0;
}
Where the audio.set code is:
void uVector::set(uStreamInfo* newStream, bool controlVector)
{
if(vector != NULL){
for(unsigned i = 0; i < stream->channels; ++i)
delete[] vector[i];
delete vector;
}
if(controlVector)
channels = 1;
else
channels = newStream->channels;
vector = new float*[channels];
for(unsigned i = 0; i < channels; ++i)
vector[i] = new float[newStream->vectorSize];
stream = newStream;
this->flush();
}
My best guess would be that it's a stack overflow issue, as it only really happens with a large number of objects, and they each run fine individually. That said, the audio stream itself runs fine and is run in a similar way. Also the loop of objects[i]->resetStream(newStream); should pop the stack after each member function, so I can't see why it would SIGSEGV.
Any observations/recommendations?
EDIT:
It was an incorrectly deleted memory issue. Application Verifier made it fault at the point of the error instead of the occasional faults identified as stemming from other locations. The problem was in the uVector stream setting function, as the intention of the class is for audio vectors using multidimensional arrays using stream->channels, with the option of using single dimensional arrays for control signals. When deleting to reallocate the memory I accidentally set all uVectors regardless of type to delete using stream-> channels.
if(vector != NULL){
for(unsigned i = 0; i < stream->channels; ++i)
delete[] vector[i];
delete vector;
}
Where it should have been:
if(vector != NULL){
for(unsigned i = 0; i < this->channels; ++i)
delete[] vector[i];
delete vector;
}
So it was deleting memory it shouldn't have access to, which corrupted the heap. I'm amazed the segfault didn't happen more regularly though, as that seems like a serious issue.
I you can spare the memory, you can try a tool like Electric Fence (or DUMA, its child) to see if it's an out of bound write that you perform.
Usually these types of segfaults (non-permanent, only occurring sometimes) are relics of a previous buffer overflow somewhere.
You could try Valgrind also, which will have the same effect as the 2 tools above, to the cost of a slower execution.
Also, try to check what's the value of the bad address you're accessing when this happens: is it looking valid? Sometimes a value can be very informative on the bug you're encountering (typically: trying to access memory at 0x12 where 0X12 is the counter in a loop :)).
For stack overflows... I'd suggest trying to increase the stack size of the incriminated thread, see if the bug is reproduced. If not after a good bunch of tries, you've found the problem.
As for windows:
How to debug heap corruption errors?
Heap corruption under Win32; how to locate?
https://stackoverflow.com/search?q=windows+memory+corruption&submit=search
I think you just made it a Stack Overflow issue. :)
In all seriousness, bugs like these are usually the result of accessing objects at memory locations where they no longer exist. In your first code block, I see you creating newStream on the stack, with a scope limited to the if statement it is a part of. You then copy it to a dereferenced pointer (*stream). Is safe and correct assignment defined for the uStreamInfo class? If not explicitly defined, the compiler will quietly provide memberwise copy for object assignment, which is OK for simple primitives like int and double, but not necessarily for dynamically allocated objects. *stream might be left with a pointer to memory allocated by newStream, but has since been deallocated when newStream went out of scope. Now the data at that RAM is still there, and for a moment will look correct, but being deallocated memory, it could get corrupted at any time, like just before a crash. :)
I recommend paying close attention to when objects are allocated and deallocated, and which objects own which other ones. You can also take a divide an conquer approach, commenting out most of the code and gradually enabling more until you see crashes starting to occur again. The bug is likely in the most recently re-enabled code.

Access violation writing location 0xcccccccc

For the past 2 days I've been stuck on a violation which I can't seem to get to go away.
I've used break points and located where the error is, but I'm just hoping one of you will know what the issue is without me having to copy+paste all my code -.-
I'm getting
First-chance exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Unhandled exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Now, a quick google search makes me think there's something peculiar going on. All the search results talk about pointers not actually pointing anywhere (0xccccccccc is a low memory address?).
I'm yet to use pointers in my code but either way I'll paste the function and point out the line the exception gets thrown (in bold):
void mMap::fillMap(){
for(int i = 0; i <= 9; i++){
for(int z = 0; z <= 19; z++){
Tile t1; // default Tile Type = "NULLTILE"
myMap[i][z] = t1;
}
}
}
Now myMap is a 2d array of type Tile. I had this working a couple of days ago until I added some other classes and it all stopped working!
Either an uninitialized pointer, or a pointer stored in memory that's been freed. I think cccccccc is the first and cdcdcdcd is the second, but it varies with compiler/library implementation.
For your particular code, probably myMap hasn't been allocated yet, then myMap[0][0] would result in an access attempt to 0xcccccccc.
It can also happen that myMap is the beginning of your class, and the class pointer was uninitialized:
class mMap
{
Tile myMap[10][20];
public:
void f() { myMap[0][0] = 0; }
};
mMap* what;
what->f(); // what is an invalid pointer
This happens because the member function is not virtual, so the compiler knows what code to run and passes the object pointer as a hidden parameter. Eventually the compiler emits a calculation like:
this + offsetof(Whatever::myMap) + z * sizeof(myMap[0]) + i * sizeof(myMap[0][0])
this, being uninitialized, is 0xcccccccc. Evidently the offsetof part is zero, and i and z are both zero the first time through your loop, so you get 0xcccccccc + 0 + 0 + 0 as the memory address.
To debug this, use the call stack and find the function that called fillMap. Then check in that function where the pointers used for member access (->) came from.
On MSVC++ and in debug mode, the debugging memory allocator sets all returned memory to 0xcccccccc, as a way to find cases of undefined behavior. In all likelihood, you never initialized myMap , or some of the pointers inside of myMap. Check your initialization code for bugs.
For all of the answers and comments happening in this question, here are good references about memory fills in Visual C++:
http://msdn.microsoft.com/en-us/library/bebs9zyz.aspx
When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?
Had similar error when I tried to fill string value in table element of my own-class type with for-loop. I declared 1000 elements in that table, so I've put something like that:
for (int i = 0; i <= 1000; i++)
{
TAble[i].name = "Some Guy";
TAble[i].age = 4;
}
Unfortunately as with string it occurred that I'm perhaps insisting on fillinf element that doesn't exist witch is element number 1000 in table. I managed to solve this by changing loop header, deleting equal sign before 1000.
Try to see whether you're not trying to call something that doesnt exist.