Search code examples
c++loopspointersdeclare

Declare pointer inside a function that is called several times


I would like to know whether or not I can do this with a function Idle() which is called several times in an opengl program.Is this OK or will I get a memory leak?

void Idle()
{
    //PXCPointF32 is a struct
    PXCPointF32 *uvmap=0;

    uvmap=new PXCPointF32[640*480];
    if(uvmap!=NULL)
    {
       //do some processing
       //fill uvmap values
    }

    if (uvmap) 
    {
        delete[] uvmap;
        uvmap=NULL;
    }
}

Solution

  • The code should work but its not optimal:

    void Idle()
    {
        //PXCPointF32 is a struct
        PXCPointF32 *uvmap=0; // why initialize to 0 only to replace its value?
    
        uvmap=new PXCPointF32[640*480];
        if(uvmap!=NULL)
        {
           //do some processing
           //fill uvmap values
        }
    
        if (uvmap) // no need to test for null before deleting
        {
            delete[] uvmap;
            uvmap=NULL; // no point setting to NULL because its local
        }
    }
    

    Instead you could do:

    void Idle()
    {
        // set it directly
        PXCPointF32* uvmap = new PXCPointF32[640*480];
    
        if(uvmap)
        {
           //do some processing
           //fill uvmap values
        }
    
        delete[] uvmap; // don't bother checking for null (delete[] does that)
    }
    

    You might also want to consider a smart pointer to clean up the memory in case of an exception:

    void Idle()
    {
        // set it directly
        std::unique_ptr<PXCPointF32[]> uvmap(new PXCPointF32[640*480]);
    
        if(uvmap)
        {
           //do some processing
           //fill uvmap values
        }
    
        // no delete[] here
    }