据说是一道面试题,谁能解释下 ps~~关于malloc的
请问运行Test函数会有什么结果?
void GetMemory2(char **p,int num)
{
*p=(char *)malloc(num);
}
void Test(void)
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,”hello”);
printf("%s",str);
}
malloc C/C++ strcpy
[解决办法]
void GetMemory2(char **p,int num)
{
*p=(char *)malloc(num);
}
void Test(void)
{
char *str=NULL;
//GetMemory(&str,100); //编译错误
GetMemory2(&str,100);
strcpy(str,”hello”);
printf("%s",str);
//内存泄露了
}
[解决办法]
未释放str指针指向的内存空间,造成内存泄漏
[解决办法]
void FreeMemory(char **p)
{
if (NULL != *p) {
free(*p);
}
*p = NULL;
}
既然有了GetMemory函数,建议有对应的FreeMemory,直接使用free不是很好