C++面试之GetMemory问题
2016-10-19 16:19
323 查看
http://blog.csdn.net/zhuxiaoyang2000/article/details/8084629
请问运行Test函数会有什么样的结果?
答:程序崩溃。 因为GetMemory并不能传递动态内存, Test函数中的 str一直都是 NULL。 strcpy(str, "hello world");将使程序崩溃。
请问运行Test函数会有什么样的结果?
答:可能是乱码。 因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是 NULL,但其原现的内容已经被清除,新内容不可知。
请问运行Test函数会有什么样的结果?
答: (1)能够输出hello (2)内存泄漏
请问运行Test函数会有什么样的结果?
答:篡改动态内存区的内容,后果难以预料,非常危险。 因为free(str);之后,str成为野指针, if(str != NULL)语句不起作用。
1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <vector> 6 #include <time.h> 7 using namespace std; 8 9 void GetMemory(char *p) { 10 p = (char *)malloc(100); 11 } 12 int main(){ 13 char *str = NULL; 14 GetMemory(str); 15 strcpy(str, "hello world"); 16 printf("%s\n",str); 17 return 0; 18 }
请问运行Test函数会有什么样的结果?
答:程序崩溃。 因为GetMemory并不能传递动态内存, Test函数中的 str一直都是 NULL。 strcpy(str, "hello world");将使程序崩溃。
1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <vector> 6 #include <time.h> 7 using namespace std; 8 9 char *GetMemory(void) { 10 char p[] = "hello world"; 11 return p; 12 } 13 int main(){ 14 char *str = NULL; 15 str = GetMemory(); 16 printf("%s\n",str); 17 return 0; 18 }
请问运行Test函数会有什么样的结果?
答:可能是乱码。 因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是 NULL,但其原现的内容已经被清除,新内容不可知。
1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <vector> 6 #include <time.h> 7 using namespace std; 8 9 void GetMemory(char **p, int num) { 10 *p = (char *)malloc(num); 11 } 12 int main(){ 13 char *str = NULL; 14 GetMemory(&str, 100); 15 strcpy(str, "hello"); 16 printf("%s\n",str); 17 // if(str != NULL){ 18 // free(str); 19 // str = NULL; 20 // } 21 return 0; 22 }
请问运行Test函数会有什么样的结果?
答: (1)能够输出hello (2)内存泄漏
1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <vector> 6 #include <time.h> 7 using namespace std; 8 9 int main(){ 10 char *str = (char *) malloc(100); 11 strcpy(str, "hello"); 12 free(str); 13 if(str != NULL) { 14 strcpy(str, "world"); 15 printf("%s", str); } 16 return 0; 17 }
请问运行Test函数会有什么样的结果?
答:篡改动态内存区的内容,后果难以预料,非常危险。 因为free(str);之后,str成为野指针, if(str != NULL)语句不起作用。
相关文章推荐
- C++面试之GetMemory问题
- C++面试之GetMemory问题
- GetMemory错误讲解(指针练习)----C++面试之GetMemory问题
- C++面试之GetMemory问题
- C++面试之GetMemory问题
- C++面试之GetMemory问题
- C++面试之GetMemory问题
- C++面试之GetMemory问题
- C/C++ 笔试面试(3)——内存管理GetMemory
- C/C++ 笔试面试(3)——内存管理GetMemory
- 多态,虚函数,纯虚函数,抽象类的相关问题(c++面试常见题目)
- 面试题——C/C++经典问题,及面试笔试题
- C/C++ 面试前 遇到问题总结
- (C/C++面试题)没看过不知道自己有多差!!!!原本以为自己C还可以,也做过几个项目了,看了这些面试问题,我傻住了!!!!
- 复制构造函数(C++面试经常询问的问题之一)
- C++面试问题
- C++中while(cin>>str)和while(cin.get(str))的结束问题
- C++高阶面试问题
- C++面试中不怎么注意和比较怪的一些问题
- C C++ OC iOS面试重点问题(一)