Why application is dying randomly?

Deadly 提交于 2019-11-28 18:41:33
CodeShane

Looks like there are a few possibilities (go figure), with quite a bit here on SO.

Might be running out of memory

Certainly one of the risks of going native!

Function call being made from two different threads at the same time

Memory Corruption


So... good luck with that one! :/

Junaid

I found out the problem.

I had been initializing a Visualizer class which object inside the onPrepareListener() of a media player.

So whenever media player was calling prepare() function, the Visualizer object had been created again and again, thus it affected the memory and resulted into app die.

Removing the Visualizer initialization code from onPrepareListener() and initializing the object only once solved the problem. Now the app no longer crashes.

The error more than likely comes from trying to delete or use a non-initialized pointer.

Since you are not directly messing with pointers, but using other libraries, it is possible that you are not initializing the library the way they want you to. Or there is a chance the library implementor neglected to initialize their pointers and simply haven't realized it because the error may or may not always reveal itself - as you have discovered.

Because pointers point to an address in memory, if a pointer is not initialized, it will likely contain a garbage value (not a valid memory address).

The error comes from trying to access/delete a memory address which does not exist or you do not have access to. The thing that makes it seem random is often memory is already pre-initialized to 0 which is also the value of NULL on most systems. Run your system/app long enough memory becomes more dirty.

Also, I have found that the chance of encountering 0's when declaring a non-initialized variable varies on different systems, so some systems may experience more crashing than others.

Personal example:

I ran into this error when I had instanced a class which had a pointer as a private member, but I forgot to initialize the pointer during class initialization.

Later when that class destructed it was trying to delete the pointer, however because the pointer was not initialized to NULL, it may or may not have some garbage value, so sometimes it would cause a crash and other times it would not.

Here's a stripped down example of the problem I recently encountered:

class BadFoo
{
public:
    BadFoo() {} // BAD! We didn't initialize the pointer
    ~BadFoo() {
        if (myPtr) {
            delete myPtr; // CRASH HERE IF INVALID ADDRESS
        }
    }
    // OTHER MEMBER FUNCTIONS HERE

private:
    int* myPtr;
}




class GoodFoo
{
public:
    GoodFoo() : myPtr(NULL) {} // GOOD! Can't be garbage value now
    ~GoodFoo() {
        if (myPtr) {
            delete myPtr;
        }
    }
    // OTHER MEMBER FUNCTIONS HERE

private:
    int* myPtr;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!