关于内存管理实例

 1 void GetMemory(char *p)
 2 {
 3     p = (char*)malloc(100);
 4 }
 5 
 6 void Test(void)
 7 {
 8     char *str = NULL;
 9     GetMemory(str);
10     strcpy(str, "helloworld");
11     printf(str);
12 }
13 
14 运行Test函数会有什么样的结果?
15 答:
16     程序崩溃;原因:1、实参是通过拷贝的方式
17     传递给行参的;str本身的值依旧是存放
18     了NULL的地址(程序头的空白地址);
19     2、malloc之后没有释放内存;
20 
21 char *GetMemory(void)
22 {
23     char p[] = "hello world";
24     return p;
25 }
26 
27 void Test(void)
28 {
29     char *str = NULL;
30     str = GetMemory();
31     printf(str);
32 }
33 运行Test函数会有什么样的结果?
34 答:打印乱码,原因:1、p字符串数组的空间是在栈上
35     开辟的,函数执行完之后,该空间释放了;
36     str指向了“栈内存”,不是NULL,但数据不存在了;
37     第23行,与char*  p = "hello world";
38     有本质的不同;(此处,p指向静态数据区,函数
39     中这样做没有问题)
40     2、printf访问栈内存,很可能存的是垃圾值。
41 
42 void  GetMemory(char **p, int num)
43 {
44     *p = (char*)malloc(num);
45 }
46 
47 void Test(void)
48 {
49     char *str = NULL;
50     GetMemory(&str, 100);
51     strcpy(str, "hello");
52     printf(str);
53 }
54 
55 
56 运行Test函数会有什么样的结果?
57 答:能正常输出,但是malloc没有free,内存泄露;
58     注意:值传递(任何时候,参数传递都是拷贝形式);
59 void Test(void)
60 {
61     char* str = (char*)malloc(100);
62     strcpy(str, "hello");
63     free(str);
64     if(str!=NULL)
65     {
66         strcpy(str, "world");
67         printf(str);
68     }
69 }
70 运行Test函数会有什么样的结果?
71 答:篡改动态内存区的内容。后果难以确定;
72     因为free(str)之后,str成为野指针;
   str仍有指向
原来指向这块空间的指针还存在,只不过现在指针指向的内容是无用的,未定义的。
    因此,释放内存后把指针指向NULL,防止指针在后面不小心又被引用。
73   if(str!=NULL)语句不起作用;
原文地址:https://www.cnblogs.com/chris-cp/p/3958474.html