错误做法:
void GetMemory (char *p) {
p = (char *)malloc(1000);
}
void Test(void){
char *str =NULL;
GetMemory(&str);
strcpy(str,"hello world");
for (int i =0; i < strlen(str);i++){
qDebug()<<str[i];
}
free(str);
}
上面代码:
void GetMemory (char **p) {
*p = (char *)malloc(1000);
} P只是 str的一个拷贝值, p开辟了空间,但是str的值还是原来的空值, p在函数运行完就释放了,str这里没有内存空间;
函数的参数会产生一个临时变量,指针也是变量,所以这里指针是值传递,改变P开辟了空间而str没有得到改变;
正确做法:
void GetMemory (char **p) {
*p = (char *)malloc(1000);
}
void Test(void){
char *str =NULL;
GetMemory(&str);
strcpy(str,"hello world");
for (int i =0; i < strlen(str);i++){
qDebug()<<str[i];
}
free(str);
}
做个int类型的代码:
void test01(int *p){
p = new int(10);
qDebug()<<p <<" "<<*p;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
int *c = nullptr;
//*c = 10;空值c,非法解引用 会导致程序崩溃 需要开辟空间才能解引用 c = new int(10)
qDebug()<<c;
qDebug()<<"-------------";
test01(c);
qDebug()<<"-------------";
qDebug()<<c;
delete c;
return a.exec();
}
输出结果:
0x0
-------------
0x17f8f0c2d60 10
-------------
0x0
可以看到 实践结果 c 拿不到函数来new的p 反而造成内存泄露