Why application is dying randomly?

前端 未结 4 671
南笙
南笙 2020-12-13 19:43

I am developing an music player app. All works fine except the app dies suddenly. Sometimes this happens when the app starts, and sometimes after running for long time. Some

4条回答
  •  有刺的猬
    2020-12-13 19:57

    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;
    }
    

提交回复
热议问题