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

前端 未结 7 1605
借酒劲吻你
借酒劲吻你 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 13:00

    You are assigning cp the value of the allocated memory. However, that's a variable on the stack: a copy of the cp in main! cp is local to the function you're in.

    What you want is a reference:

    void func(char *& cp)
    

    This will alias cp to be the parameter passed in.

提交回复
热议问题