zoukankan      html  css  js  c++  java
  • 关于内存管理实例

     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)语句不起作用;
  • 相关阅读:
    普通PC硬盘与DVR专用硬盘主要差别
    远程监控,需要安装控件,安装前对浏览器设置如下。硬盘录像机,采集卡通用...
    SQL Server不允许进行远程连接
    远程备份(还原)SQL2000数据库
    安装MSDE时提示 实例名无效
    冰雹,刨冰,危险人物
    北京首现最严重的0day攻击方式
    孤独,寂寞,无聊
    大家平时都在做什么
    华山之旅
  • 原文地址:https://www.cnblogs.com/chris-cp/p/3958474.html
Copyright © 2011-2022 走看看