C++ allocating dynamic memory in a function - newbie question

前端 未结 7 1723
借酒劲吻你
借酒劲吻你 2021-01-31 12:05

I\'m investigating a memory leak and from what I see, the problem looks like this:

int main(){
    char *cp = 0;
    func(cp);
    //code
    delete[] cp;
}

voi         


        
7条回答
  •  时光取名叫无心
    2021-01-31 12:56

    As GMan and Neil mentioned, in order to work you will have to change func to:

    char* func();

    or void func(char*& p);

    which will solve your immediate problem.

    There is, however, a maintenance problem. In either case, func returns a pointer. What is not clear to the user of func is that returned pointer will have to be deleted. For this reason, generally avoid this construct unless 100% necessary. Rather:

    1. Help the user allocate the correct amount of memory which can then be passed to func
    2. Use an object to store the allocated memory. The object can then delete the character array when it is destructed.

    So for C++ code,I would recommend:

    
    class CBuf
    {
    public
        CBuf() 
        {
            iBuf = new char[100];
        }
        ~CBuf
        {
            delete[] iBuf;
        }
        char* func()
        {
            //do stuff;
            return iBuf;
        }
    private:
        char* iBuf;
    };
    
    int main()
        {
        CBuf cb;
        char* mychar = cb.func();
        //do stuff with character array
    
        //destructor gets called here because cb goes out of scope
        }
    

    However, in C programming especially, it might be 100% necessary to have some sort function to create the array. Therefore in C programming you can replace the destructor with a CreateCBuf and DestroyCBuf function. In this way the user of your library will know that the buffer returned needs to be destroyed.

提交回复
热议问题