澳网2018赛程:(经典C++面试题)指针、双指针、内存分配

来源:百度文库 编辑:中财网 时间:2024/04/28 16:11:51
 
注意理解指针的值指针的地址!指针也是分两部分的! 绿岸还考了另外一种情况:当调用函数动态分配内存成功后,再释放掉该内存,此时对指向该动态内存的指针进行操作!这是非法的,这是野指针,不知道指向什么。(用if(str!=NULL)来判断,str不是空但指向了未知内存,篡改它会造出严重问题!) 1、分配了以后一定要释放,不然会造成内存泄露。2、分配前和释放后都将指针设为NULL,避免野指针。  (1):void GetMemory(char *p)
{
p=(char*)malloc(100);
}

void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str,"helloworld");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:程序崩溃。因为GetMemory并不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str,"helloworld");将使程序崩溃。
(2):
char *GetMemory(void)
{
char p[]="helloworld";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
请问运行Test函数会有什么样的结果?
答:可能是乱码。因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原先的内容已经被清除,新内容不可知。
 (3):
void GetMemory2(char **p, int num)
{
*p = (char*)malloc(num); //对*p进行操作就是对str进行操作
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:(1)能够输出hello(2)内存泄漏   以下是一个没有错的例子:

char * MyFunc (void)
{
 char *p =new char[20];
   
 return p;
}
void main(void)
{
 char *str = NULL;
 str = MyFunc();
 if(str!=NULL)
 {
  strcpy(str,"Hello,baby");
  cout<< str << endl;
  free(str);
  str=NULL;
 }
 
}

 //------------------------------------------------- 下面是我自己的理解:(1)、char *str = NULL;//指针str上的值为NULL,GetMemory(str);//str将自己的值赋给p,此时p的值为NULL进入GetMemory函数,p=(char*)malloc(100);//申请动态内存空间,并将内存基地址的值(假设为S)赋给p此时,p的值为s。但GetMemory函数所进行的一切,都与str无关,p只是拷贝了str的值。所以str的值还是NULL,因此,对str进行赋值,将会使程序崩溃
(2)、char p[]="helloworld";return p; //"helloworld"在栈内存中,p指向此栈内存基地址,但函数运行结束后,此内存将被释放。str = GetMemory();//str指向一片已被释放的空间,其值不可知
(3)、GetMemory(&str, 100);//将str的地址赋给p,而不是值。此时*p为str的值*p = (char*)malloc(num);//更改str的值,即更改str指向的内存空间因此,str能打印出"hello"