天天看點

Getmemory函數問題

有關記憶體的程式問題

(1)

void GetMemory(char*p)
{
p = (char*)malloc(57);
}
void main()
{
char*str = NULL;
GetMemory(str);
strcpy(str, "bit C++");
printf(str);
}      

程式崩潰,由于GetMemory采用值傳遞,p的值沒有使void中的str變化

(2)

char*GetMemory(void)
{
char p[]="bit C++";
return p;//傳回p的首位址
}
void main()
{
char*str = NULL;
str = GetMemory;   
printf(str);
}      

程式亂碼

(3)

char GetMemory(char**p)
{
*p=(char*)malloc(57);
}
void main()
{
char*str = NULL;
GetMemory(&str);
strcpy(str, "bit C++");
printf(str);
}      

可以輸出bit C++,但是記憶體洩露,應該free(str);

(4)

void main()
{
char *str = (char*)malloc(57);
strcpy(str, "bit");
free(str);
if (str != NULL)
{
strcpy(str, "C++");
printf(str);
}
}      

繼續閱讀