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

  • 相关阅读:
    各进制转换
    免root xshell连接termux
    sqlmap怎么拿shell
    SSRF漏洞
    国外安全网站、社区论坛、博客、公司、在线工具等整合收集
    渗透测试常用工具问题总结
    cdn绕过
    xss注入
    永恒之蓝(msf17010)kali复现
    文件上传漏洞和绕过
  • 原文地址:https://www.cnblogs.com/fangying7/p/3788559.html
Copyright © 2011-2022 走看看