zoukankan      html  css  js  c++  java
  • C语言动态内存分配

    考虑下面三段代码:

    片段1

    void GetMemory(char *p)
    {
    p = (char *)malloc(100);
    }
    void Test(void)
    {
    char *str = NULL;
    GetMemory(str);
    strcpy(str, "hello world");
    printf(str);
    free(str);
    }

    片段2

    char *GetMemory(void)
    {
    char p[ ] = "hello world";
    return p;
    }
    void Test(void)
    {
    char *str = NULL;
    str = GetMemory();
    printf(str);
    }

    片段3

    void GetMemory(char **p, int num)
    {
        *p = (char *) malloc(num);
    }
    
    void Test(void)
    {
    char *str = NULL;
    GetMemory(&str, 100);
    strcpy(str, "hello world");
    printf(str);
    }

    在执行代码:

    int main()
    {
    
        Test();
    
        return 0;
    }

    上面三个片段中,1和2根本无法得到正确的结果。片段1甚至会引发程序崩溃!!!

    阅读了林锐博士《高质量C/C++编程指南》,在内存管理方面发现确实有很多说道。。。

    片段一中,Test 函数的语句 GetMemory(str, 200) 并没有使 str 获得期望的内存, str 依旧是 NULL。

    毛病出在函数 GetMemory 中。编译器总是要为函数的每个参数制作临时副本,指针参数 p 的副本是_p ,编译器使_p = p 。如果函数体内的程序修改了_p 的内容,就导致参数 p 的内容作相应的修改。如果非得要用指针参数去申请内存, 那么应该改用 “指向指针的指针!!!!


    片段2的错误显而易见,不能return 指向栈内容的指针!

  • 相关阅读:
    Superwebsocket 模拟微信聊天室
    python杂记-6(time&datetime模块)
    python杂记-5(装饰器)
    python杂记-4(迭代器&生成器)
    python杂记-3(购买商品)
    python杂记-2(python之文件)
    python杂记-1(os模块)
    淘宝链接中的spm参数
    分布式Web服务器架构(转)
    asp.net网站增加虚拟目录,用来访问网站图片。
  • 原文地址:https://www.cnblogs.com/fangying7/p/3788559.html
Copyright © 2011-2022 走看看