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

前端 未结 7 1748
借酒劲吻你
借酒劲吻你 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:01

    void func(char *cp){
        cp = new char[100];
    }
    

    In this function, char *cp is a "pointer being passed by copy" what means that they are pointing to the same memory address but they are not the same pointer. When you change the pointer inside, making it to point to somewhere else, the original pointer that has been passed will keep pointing to 0.

提交回复
热议问题