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 指向栈内容的指针!

  • 相关阅读:
    NFS 规格严格
    Spring 规格严格
    如何做好软件功能测试 规格严格
    51CTO上不错的文章 规格严格
    一个好网站 规格严格
    系统小贴士 规格严格
    编译Zabbix 规格严格
    JS学习 规格严格
    杂项 规格严格
    MySQL 自增ID 规格严格
  • 原文地址:https://www.cnblogs.com/fangying7/p/3788559.html
Copyright © 2011-2022 走看看