Segmentation Fault : Delete[]

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • IanWright
    New Member
    • Jan 2008
    • 179

    #1

    Segmentation Fault : Delete[]

    I've got a segmentation fault problem and am wondering if anyone can help me. I'll apologise now for the fact that I've about a week experience using C++, but I'll try my best to follow any replies :)

    Firstly I'm developing in C++ on a Linux machine (using g++ compiler).

    My application iterates through a process around about 120 times during testing. It appears that I randomly receive segmentation faults during one of these iterations though sometimes I'll reach the end fine. I've believe I've managed to track the problem using a Linux debug tool:

    "#3 0x0806d1cf in Heap::Deallocat e() (this=0x4300152 0) at Heap.cpp:40"

    I believe Heap is a custom made class, and the appropriate method is:


    [CODE=c]37 void Heap::Deallocat e ()
    38 {
    39 if (m_HeapData)
    40 delete[] m_HeapData;
    41 if (m_Indexes)
    42 delete[] m_Indexes;
    43 if (m_FreeSlots)
    44 delete[] m_FreeSlots;
    45
    46 Initialise () ;
    47}[/CODE]

    which suggests the delete[] m_HeapData; line. Where [CODE=c]HeapData* m_HeapData ;[/CODE] and HeapData is another class.

    I am struggling to grasp why this would fail sometimes and not others and would appreciate any guidance. If there is any more information that's useful please let me know. If I've not given enough code for an example, let me know what else might be useful.

    Thanks for the help.

    Just thought that the creation of m_HeapData may be useful...

    [CODE=c]void Heap::Create (int size)
    {
    assert (m_HeapData == 0) ;

    // Number of slots available (can be extended)
    m_nMax = size ;

    // Create the arrays needed for the heap
    m_HeapData = new HeapData [m_nMax] ;
    m_Indexes = new int [m_nMax] ;
    m_FreeSlots = new int [m_nMax] ;
    ....
    }[/CODE]

    Ian
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Probably because nin Heap::Deallocat e() the deleted pointers are notr set ot zero after they are deleted. Should the method be called again, you will crash immediately.

    The code should look like:
    [code=cpp]
    void Heap::Deallocat e ()
    {
    delete[] m_HeapData;
    delete[] m_Indexes;
    delete[] m_FreeSlots;
    m_HeapData = 0;
    m_Indexes = 0;
    m_FreeSlots = 0;

    Initialise () ;
    }
    [/code]

    You don't need to check for zero before deleting. This isn't C.

    Also, m_ does not make these variables member variables. They are member variables if you use the this pointer:
    [code=cpp]
    void Heap::Deallocat e ()
    {
    delete[] this->HeapData;
    delete[] this->Indexes;
    delete[] this->FreeSlots;
    this->HeapData = 0;
    this->Indexes = 0;
    this->FreeSlots = 0;

    Initialise () ;
    }
    [/code]

    Also, this is not a destructor. Therefore, you can't delete unless you know you are deleting the final copy of thse pointers. And you can't tell that. You should not be using naked pointers here. You should be using reference counted handles (a.k.a. managed or smart pointers). Theres is an article on handles in the C/C++ HowTos. Inside that article is ta template for a referecne counted handle that you can copy and use in your own code. If you do this, your errors will go away.

    Comment

    • IanWright
      New Member
      • Jan 2008
      • 179

      #3
      weaknessforcats , thanks for the reply. I've looked at your remarks, and I believe that it does this if I provide a little more detail that now seems more important.

      The Deallocate() method is only called from the destructor of Heap if the first thing, there are no references to it anywhere else. Secondly the Initialise method is as follows:

      [CODE=c]void Heap::Initialis e ()
      {
      m_HeapData = 0 ;
      m_Indexes = 0 ;
      m_FreeSlots = 0 ;
      m_nFree = 0 ;
      m_nNum = 0 ;
      m_nMax = 0 ;
      m_nHeapTotal = 0 ;
      m_nHeapPeak = 0 ;
      }
      [/CODE]

      So it should also reset all those values to 0. Honestly looks a bit of a strange way to do things to me, but I didn't write it so will have to deal with it.

      Comment

      • IanWright
        New Member
        • Jan 2008
        • 179

        #4
        I've got an extension to this question if you don't mind...

        The stacktrace reports that the problem lies within a DLL that has been used for sometime in the Heap::Deallocat e() method I'm led to believe. This DLL operates to carry out 2 different function:

        1) The first function works and has been running for several months without problem. It uses the Heap object in the following manner:

        [CODE=cpp]
        Heap heap ;
        HeapData data ;
        ...
        heap.Insert(dat a) ;
        [/CODE]

        2) The second function which hasn't been used frequently uses a different approach, opting for the 'new' keyword like so. And later uses delete[] to free the resources up.

        [CODE=cpp]
        Heap used by Isochrone:
        Heap* m_pIsoHeap ;
        m_pIsoHeap = new Heap ;
        [/CODE]

        When delete[] is called, the destructor is used and within the destructor the Deallocate method is called. If the 'new' keyword isn't used, does this mean that when C++ deals with the memory management, that the destructor will not get called, and hence the deallocate method will never be used?

        If this is the case, then the I believe the Deallocation code may not be thread safe, and hence causing me some problems! :)

        Can anyone confirm if this way of thinking is correct? Thanks very much.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Destructors are called when an object goes out of scope. However, an object allocated by new newver goesout of scope. The pointer might, but not the object. You have to manually call delete to remove the object.

          Regardless of the method of removal (stack objecty going out of scope or you calling delete), the destructor will be called so you can clean up any allocated data members.

          You just need to be certain in that destructor that you don't clean up something you didn't allocate. That means deleting a pointer you go from somewhere inside a destructor is a big no-no.

          You need to use handles.

          Comment

          • madanear
            New Member
            • Mar 2008
            • 1

            #6
            I have got the segmentation fault problem and I am wondering if anyone can help me.

            Firstly I'm developed in C++ on a Linux machine (using g++ compiler).
            I am going to develop the Visual Surveillance application using the Network Camera as a hardware.

            Program No. 1:

            if (mysql_query(co nn, "truncate video")) {
            //fprintf(stderr, "%s\n", mysql_error(con n));
            // exit(0);
            }
            /* end of MySQL */

            if(argc>1){

            long current=0;
            CURL *curl;
            char filename[200];
            sprintf(filenam e,"temp%d.jpg", videoNumber);
            FILE *file;
            curl_global_ini t(CURL_GLOBAL_A LL);

            curl = curl_easy_init( );
            char buf[200];
            //printf("Test %s\n",inpFile);
            if(strlen(inpFi le)==2)
            {
            if(curl){

            curl_easy_setop t(curl, CURLOPT_VERBOSE , 0);
            curl_easy_setop t(curl, CURLOPT_WRITEFU NCTION, write_data);
            /* get the first document */
            sprintf(buf,"ht tp://root:amol@1234@ 172.21.107.207/axis-cgi/jpg/image.cgi?resol ution=320x240") ;
            curl_easy_setop t(curl, CURLOPT_URL,buf );
            int i=0;
            CallAR.CallBack ActivityReco(in pFile,dumpDir,d oorfile,videoNu mber);
            while(!signaled ){
            file=fopen(file name,"w");
            curl_easy_setop t(curl,CURLOPT_ WRITEDATA,file) ;
            curl_easy_perfo rm(curl);
            fclose(file);

            //printf("Test\n" );
            IplImage *NtwkImage=cvLo adImage(filenam e,1);
            current++;
            char buffer[50];
            sprintf(buffer, "dumpDir/%010d.jpg",curr ent);
            //printf("Test\n" );
            if(!CallAR.fram e_call(inpFile, dumpDir,NtwkIma ge,conn,videoNu mber)) break;
            cvReleaseImage( &NtwkImage);
            }
            curl_easy_clean up(curl);
            }
            }
            else{
            CallAR.CallBack ActivityReco(in pFile,dumpDir,d oorfile,videoNu mber);
            IplImage* I=0;
            while(!signaled ){
            if(!CallAR.fram e_call(inpFile, dumpDir,I,conn, videoNumber)) break;
            }
            }
            exit(0);
            }
            return 0;
            }

            and


            Program No. 2:

            int CallBackAR::fra me_call(char* inpFile, char* dumpDir,IplImag e* NtwkImage,MYSQL *conn,int vno){
            //printf("TESTING \n");
            timeval tim;
            double t1,t2;
            if(strlen(inpFi le)==1)
            {
            gettimeofday(&t im, NULL);
            t1=tim.tv_sec+( tim.tv_usec/1000000.0);
            image = useStreamer();
            gettimeofday(&t im, NULL);
            t2=tim.tv_sec+( tim.tv_usec/1000000.0);
            //printf("%.6lf Before Grab Time\n", t1);
            //printf("%.6lf After Grab time\n", t2);

            }

            else if(strlen(inpFi le)==2)
            {
            gettimeofday(&t im, NULL);
            t1=tim.tv_sec+( tim.tv_usec/1000000.0);
            image=NtwkImage ;
            //pthread_mutex_l ock (&mutexsum);
            //image=cvLoadIma ge("image.cgi?r esolution=320x2 40",1);
            //pthread_mutex_u nlock (&mutexsum);
            gettimeofday(&t im, NULL);
            t2=tim.tv_sec+( tim.tv_usec/1000000.0);

            //printf("%.6lf Before Grab Time\n", t1);
            //printf("%.6lf After Grab time\n", t2);
            }
            else{
            gettimeofday(&t im, NULL);
            t1=tim.tv_sec+( tim.tv_usec/1000000.0);

            if( !cvGrabFrame( capture )) return 0;
            cimage = cvRetrieveFrame (capture);
            gettimeofday(&t im, NULL);
            t2=tim.tv_sec+( tim.tv_usec/1000000.0);
            //printf("%.6lf Before Grab Time\n", t1);
            //printf("%.6lf After Grab time\n", t2);
            cvResize(cimage ,image);
            }


            Please help me as early as possible since I have solve this issue today.

            Comment

            • weaknessforcats
              Recognized Expert Expert
              • Mar 2007
              • 9214

              #7
              Originally posted by madanear
              I have got the segmentation fault problem and I am wondering if anyone can help me.
              I would like to but this is IanWright's post.

              Start your own thread, please, rather than hijack someone else's.

              Comment

              Working...