" malloc error pointer being freed was not allocated " error only in simulator: - c++

When I debug on actual devices, there is no error, but when I use the simulator, Xcode's debugger console displays the following error when running:
malloc: *** error for object 0xaaaaaaaa: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
The error always happens at the same line, which is in the constructor of another class:
Segment *segment = new Segment(0.0,0.0,3.0,1.3,10);
this->segments.push_back(segment); // Malloc error at this line
My Segment class:
class Segment {
private:
float ajc;
float frl;
std::unordered_map<int,int> jgrc;
std::vector<int> lorb;
public:
std::tuple<float,float> getMjt();
float getBuw();
….
Segment(float a, float f,float g, float lo, float u){
……
};
};
On the simulator, regardless of iOS version, the error appears. On devices, regardless of version, there is no error.
I have heard about the rule of 3, but in this case I don't think I need to apply it because the default compiler supplied code should work (unless I'm mistaken). What am I doing wrong, and how can I fix this ? Since there is no error reported on devices, should i ignore it ?

First put a NULL check to avoid the run time error. I tried a pseudo code on VS and it seemed to work. I hope your vector is similar.
Segment *segment = new Segment(0.0, 0.0, 3.0, 1.3, 10);
std::vector<Segment*> vec;
if (NULL != segment)
vec.push_back(segment);
I think there is some problem with your simulator not working fine.

The solution works, but I don't understand why. If someone with more c++ can explain it well, I will mark that as the correct answer.
The following code runs in the constructor of my class that creates the segments:
Segment *segment = new Segment(0.0,0.0,3.0,1.3,10);
this->segments.push_back(segment); // Malloc error at this line
First, I used objects instead of the pointer. Then I moved the code out of the constructor, and instead call it immediately after creating an instance of the class.
Say my class is:
class MyClass{
std::vector<Segment> segments;
}
I do :
MyClass *foo = new MyClass();
foo->createSegments();
Where:
createSegments(){
Segment segment = Segment(0.0,0.0,3.0,1.3,10);
segments.push_back(segment);
}
I'm not very experienced with C++, so I don't know why this works.I also still don't know why the original error only appeared in the simulator.

Related

debugging segmentation fault

I have a c++ program that compiles fine under gcc (4.8.1), icpc (13.1.3), clang++ (3.3) and runs okay except for the clang++ version which crashes with segfault. When I try to run this in the gdb or lldb debugger, I get EXC_BAD_ACCESS with address 0x0. The crash occurs in a member function of a helper class and the debugger claims that this has value 0x0. However going up one level, the pointer pimpl of the helper class is reported to have a non-null value and I can access its data, which look perfectly sensible.
here is some pseudo code (... is not the ellipse, but means "some parameters")
struct helper;
struct foo {
helper* pimpl;
foo(...);
void bar(...);
};
struct helper {
helper(...);
void hbar(...)
{
// crash here with *this = 0x0 according to debugger
}
};
foo::foo(...) : pimpl(new helper(...)) {}
void foo::bar(...)
{
pimpl->hbar(...); // pimpl NOT 0x0 according to debugger ??!
}
What could have gone wrong and how can I find out? Note: the question is NOT: "what is wrong with my code?"
edit 1 Perhaps it is worth mentioning that some of the arguments passed to helper::hbar() have been "optimised away by the compiler", according to the debugger, at the point of foo::bar()), while they have address 0x0 within helper::hbar()
edit 2 If I print out the value of this from within helper::hbar() the error does not occur.
edit 3 The error occurs with -O0 as well as -O2.
edit 4 The first arg of helper::hbar() was taken via const reference. If I change that to by value, everything works fine .... That argument was a spatial vector, similar to std::array<double,3>.
One way to do it - create a log file, print value of pimpl/some variable belonging to pimpl before
pimpl->hbar(...);,
and inside
pimpl->hbar(...);
Compare output from different compilers, try narrow down the problem that way adding more output to log file as you start seeing divergence...

New stops my object working correctly

I've had to completely rewrite this problem as I've found out a lot more about it now.
Background:
My programme is drawing some 3d objects under directx11. I have a class that contains the data, pointers, and functions needed to draw the required 3d objects. Everything was working well. I could create many different 3d objects and draw them wherever I wanted. Great!
Then I needed to put them in a container and into a vector so I didn't have to create each object manually, this was where the trouble started; it would crash 1 time in 5 or so.
Unhandled exception at 0x00C308C1 in SpritesNTextN3D.exe: 0xC0000005: Access violation reading location 0xFFFFFFFF.
It crashed when using vectors and maps. I continued this line of enquiry and tried using a pointer and new:
ThreeD_Cube* threed_cube_p;
threed_cube_p = new ThreeD_Cube;
This also caused it to crash when I ran its draw function.
threed_cube_p->draw(threeD, camera, d3dContext_mp);
However if created as a standard object:
ThreeD_Cube threed_cube_;
The draw function never crashes.
threed_cube_-.draw(threeD, camera, d3dContext_mp);
Likewise, creating a pointer to threed_cube_ works as expected.
Question:
What is new doing that the default constructor isn't. Is there anything I should be looking at to resolve this problem?
It seems you have a good constructor, but bad/insufficient (default) assignment operator and bad/insufficient (default) copy constructor.
Let's see why some parts of your code works but some not:
//threed_cube_vec[0].draw(threeD, camera, d3dContext_); // doesnt work!!!
It tells you what's in threed_cube_vec[0] is a bad/corrupted object.
ThreeD_Cube test = threed_cube_vec[0]; // But, if I copy it...
In this line, (for some reason) firstly the constructor is called, which gives you a good object. Then the "=" is called, partially the object is modified, but the object is still good since it was already good before the "="
ThreeD_Cube* test = &threed_cube_vec[0];
As for a pointer, it is the essentially object threed_cube_vec[0] itself, so still corrupted.
ThreeD_Cube test = threed_cube_vec[0];
vector<ThreeD_Cube> test2;
test2.push_back(test);
test2[0].draw(threeD, camera, d3dContext_);
This does not fixed the problem as you said. "test" is a good object, but when you push_back(test) into test2, a copy is pushed back [if you change it to test2.push_back(std::move(test) , the problem could be gone]. Since the copy constructor is incomplete, the object in test2[0] is corrupted. Similar scenario happens with your map.
Conclusion: if an object is originated from the constructor, you get a good object; if an object is originated from a copy constructor, it is corrupted.
A quick test you can do: resize your vector after you declare it, the error should be gone temporarily.
Crash after m = XMMatrixIdentity() - aligment memory in classes?
This topic covers the answer to my problem. I eventually tracked it down to XMMATRIX causing crashes with new due to memory alignment.
Here's a shortened version of the problem:
void matrix_test_pointer()
{
XMMATRIX* xmmatrix_p;
xmmatrix_p = new XMMATRIX;
*xmmatrix_p = XMMatrixIdentity(); // this is where it crashes
}
void matrix_test()
{
XMMATRIX xmmatrix;
xmmatrix = XMMatrixIdentity();
}
int main()
{
string wait;
matrix_test();
cout << "matrix_test() completed.\n";
matrix_test_pointer();
cout << "matrix_test_pointer() completed.\n"; // If it does you are lucky :)
cin >> wait;
return 0;
}
Chances are matrix_test will complete but it will crash before pointer will complete.

Why does the compiler not reserve enough space on the stack?

I have a C++ class Matrix22 with an array and a default constructor:
class Matrix22{
/* something more */
double mat[2][2];
Matrix22(){
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
mat[i][j] = i==j ? 1.0 : 0.0;
}
};
I used it in my program and got a segmentation fault. As the rest was quite difficult and complicated I wrote a simple test routine, that just calls Matrix22(). No more seg fault.
I then ran gdb to debug the problem. If I call the constructor from the separate test routine, gcc reserves some memory for the member mat. I can navigate through the stack and see the return address some bytes after the array.
In the main program the compiler does not reserve enough space. The first element (mat[0][0]) gets written but any futher write just overwrites the next stack frame. I can also verify that as before the constructor the command btreturns a correct backtrace, where after the critical assignment the backtrace is corrupted.
So my question is: Why does in one case the compiler (or the linker?) reserve not enough space for the array, while in the other case that is not happening?
PS: Both "test cases" are compiled with the same compiler and flags and alsolinked against the same object files.
edit:
Here is the "simple" test case that works without seg fault:
void test_Matrix22()
{
Framework::Math::Matrix22 matrix;
}
The code with creates a seg fault is in the class ModuleShaddower (intermixed header and implementation):
class ModuleShaddower{
public:
ModuleShaddower(PVModule& module, const EnvironmentalSetup& setup, const Position& position);
private:
Matrix22 rotMatrix90;
};
ModuleShaddower::ModuleShaddower(PVModule& module, const EnvironmentalSetup& setup, const Position& position)
: module (module), position(position), setup(setup), logger(LoggerFactory::getLoggerInstance())
{
double mat[][2] = {{0, -1},{1, 0}}; // This line will never be reached
rotMatrix90 = Matrix22(mat);
}
As you see, it is quite from within the rest. I will maybe try to extract the problematic code but I think this won't help much.
If your ModuleShaddower contructor code is not getting reached (as per you code comment) then something in your constructor initialization list (related to contructuction of module, possition etc) is causing the problem.
The problem was due to the fact that two object files in different locations had the same name. In the resulting static library, that was created from that object code, sometimes the wrong file gets replaced (both were called Shaddower.o). As I renamed one of the files all went well and no more errors.
I do not know the exact origin of this problem but it is solvable like that.

Cause for crash in std::set::insert

I am trying to debug a problem where our program crashes (segfault) in the ´addToOurSet` method below:
class SomeClass {
// ( ... )
void addToOurSet(SomeOtherClass* obj) { ourSet.insert(obj); }
std::set<SomeOtherClass*> ourSet;
};
The crash is hard to reproduce due to (among other things, the complexity and large data size involved, and failure to reproduce in a debug build; the above example is obviously highly simplified). The traceback shows the crash occurring in:
std::_Rb_tree<...>::insert_unique(SomeOtherClass* const&)
My question is: What could cause the ourSet.insert(...) method to crash? As far as I understand, there is nothing with the inserted object itself that could cause it, since it is a pointer. Correct? So am I looking at a problem with the set itself? Obviously, if the set pointer is invalid for some reason, the call could crash, but could for example some operation on the set cause it to be invalid in this way (like for example deleting past its end or something that is forbidden)?
There are several possibilities:
The set itself is invalid (the enclosing SomeClass instance has been deleted, or is being accessed through a dangling pointer etc).
There's a memory corruption somewhere.
I'd probably start with valgrind or a similar tool.
I ran across a similar problem recently. It turned out that I had 2 slightly different declarations for the same class. In foo.h:
class SomeClass {
// ( ... )
void addToOurSet(SomeOtherClass* obj) { ourSet.insert(obj); }
std::set<SomeOtherClass*> ourSet;
};
and in bar.h:
class SomeClass {
// ( ... )
std::vector<SomeOtherClass*> ourSet;
};
It compiled fine but segfaulted deep in <set>.

Segmentation fault calling std::map::clear

I have been struggling with a segmentation fault for months, now I'm here to ask for help.
The segmentation fault appears when I call the following function
void foo(..., std::map<MyClass*, double> & x) {
if ( !x.empty() ) x.clear();
...
}
Class A {
private:
map<MyClass*, double> _N;
public:
void f(...) {
foo(..., _N);
...
}
};
//in main routine, the function is called in a loop
A a;
while(...) {
a.f(...);
}
Using gdb, I tacked the error to the line calling the clear() function, it shows "double free or corruption" error, and the program aborts at calling c++/4.1.2/ext/new_allocator.h:94 delete(__P) which further calls free() from the gnu library /lib64/libc.so.6. But since the elements in the map are not allocated by new, why it still calls free() to clear it up. I would really appreciate your comments. Thank you.
Given that the map is owned by another object it suspiciously sounds that the map-owning object was already deleted when the clear was called.
Also note that names starting with underscore and a capital letter are reserved for the implementation - you aren't allowed to use them.
The code looks fine to me. At least with the limited context you have provided. Usually when I run into issues like this I will simply run the valgrind memcheck tool to find the place were the first "delete" happened. Once you know that, these issues can be pretty simple to solve.