简体   繁体   中英

“ malloc error pointer being freed was not allocated ” error only in simulator:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM