您的位置:首页 > 编程语言 > C语言/C++

C++面试之GetMemory问题

2016-10-19 16:19 323 查看
http://blog.csdn.net/zhuxiaoyang2000/article/details/8084629

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)语句不起作用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: