zoukankan      html  css  js  c++  java
  • C 无返回值函数传入一级指针后造成的内存泄露问题

    错误代码如下示:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void get_memory(char *p, int num)
    {
      p = (char *)malloc(sizeof(char)*num);
    }
    
    int main(int argc,char *argv[])
    {
      char *str = NULL;
      get_memory(str, 100);
      strcpy(str, "hello");
      printf("resut: %s
    ", str);
    
      return 0;
    }

    linux下执行结果

    $ ./tt
    Segmentation fault

    析:

    调用函数 get_memory() 后,p将被系统释放,但由于malloc是在堆中分配的,只有当程序结束后才释放,这样将造成内存泄露。

    linux下,由于函数调用后p的值变为了0x00,这样再执行strcpy时由于访问了无效地址而出现了段错误。

    正确代码如(采用了二级指针方式)下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void get_memory(char **p, int num)
    {
      *p = (char *)malloc(sizeof(char)*num);
    }
    
    int main(int argc,char *argv[])
    {
      char *str = NULL;
      get_memory(&str, 100);
      strcpy(str, "hello");
      printf("resut: %s
    ", str);
    
      return 0;
    }

    执行结果如下:

    $ ./tt
    resut: hello
  • 相关阅读:
    顺序查找
    折半查找
    KMP
    php长时间的脚本,报502
    AcWing 27. 数值的整数次方
    acwing 25. 剪绳子
    Best Cow Line <挑战程序设计竞赛> 习题 poj 3617
    acwing 23. 矩阵中的路径
    AcWing 34. 链表中环的入口结点
    AcWing 33. 链表中倒数第k个节点
  • 原文地址:https://www.cnblogs.com/aqing1987/p/4349553.html
Copyright © 2011-2022 走看看