CSDN上看到关于C++ 指针参数。。无语
在CSDN 上看到这么三个题,下面各种千奇百怪的回答真是参差不齐。。 只能用很无语来回答。
1。void GetMemory(char *p) { p = (char *)malloc(100); } void Test(void) { char *str = NULL; GetMemory(str); strcpy(str, "hello world"); printf(str); } 2。char *GetMemory(void) { char p = "hello world"; return p; } void Test(void) { char *str = NULL; str = GetMemory(); printf(str); }
3。Void GetMemory2(char **p, int num) { *p = (char *)malloc(num); } void Test(void) { char *str = NULL; GetMemory(&str, 100); strcpy(str, "hello"); printf(str); }
只能自言自语的说下了,尽管很基础。。。
第一个在GetMemory 方法体里面会产生一个临时的局部副本指针_p=(char *)malloc(100);_p=p, 这里 _p 申请了堆空间,只是改变了_p所指内容的地址(即_p),但是p是没有变化。 在GetMemory方法体结束后,_p 会在堆里面没有free,有可能内存泄露。。
第二个p是栈内存,是系统自动分配的,函数体后会制动销毁,返回的内容是未知地。。。
第三个同第一个MS是一样的。。 这时候依然_p=p, _p分配空间,改变了_p,p有值了,即str有地址了,但是p其实是未知的,出来后_p在堆里面没有free,有可能内存泄露
为了不让内存泄露
可以改造为==>
char *GetMemory2( int num) { char *p = (char *)malloc(num); return p; } void Test(void) { char *str = GetMemory(str, 100); strcpy(str, "hello"); printf(str); free(str); }