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

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

    The parameter cp is a local variable of the function - changing it does not alter anything outside the function. A better way to write the function is:

    char * func(){
        return new char[100];
    }
    

    And not to do directly with your question, but you should probably be using std::string and std::vector rather than dynamically allocated arrays.

    0 讨论(0)
提交回复
热议问题