问题描述
我正在调查内存泄漏,从我看到的,问题如下:
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;
}
void func(char *cp){
cp = new char[100];
}
在代码注释中,我希望cp指向分配的内存,但它仍然是一个空指针,意味着我从来没有删除内存。
At the //code comment, I expected cp to point to the allocated memory, but it still is a null pointer meaning I never delete the memory. What am I doing wroing?
推荐答案
void func(char *cp){
cp = new char[100];
}
在此函数中,char * cp是一个 strong>通过复制传递,这意味着它们指向同一内存地址,但它们不是相同指针。当你改变指针在里面,使它指向别的地方,已经传递的原始指针将保持指向0。
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 somewhere else, the original pointer that has been passed will keep pointing to 0.
这篇关于C ++在一个函数中分配动态内存 - 新手问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!