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
  • 相关阅读:
    spring 事务
    spring jdbc学习1
    css学习2
    css学习1
    spring aop 学习1
    spring学习1
    jQuery学习笔记1
    JavaScript学习笔记1
    springboot+quartz+vue+socket实现的定时任务加任务日志实时查看
    hadoop hbase数据备份异常
  • 原文地址:https://www.cnblogs.com/aqing1987/p/4349553.html
Copyright © 2011-2022 走看看