跨函数使用malloc函数

来源:互联网 发布:淘宝点卡进货渠道 psn 编辑:程序博客网 时间:2024/05/21 11:00

在C的编程中,有时候需要在函数内进行动态内存分配来提高函数的可用性和移植性,但如果忽略对动态内存的释放,便会导致程序会有内存泄露。以下将会介绍一些正确和错误的方法。

一、正确的跨函数使用malloc的方法

1、通过二级指针进行传递      void Getmemory(char **p,int n)

# include # include void Getmemory(char **,int);int main(){char *p = NULL;int n = 10;Getmemory(&p,n);if(p == NULL){    return -1;}printf("%d\n",p);for(int i=0;i

可以发现程序运行正确,而且其对应指针的数值也改变了

2、通过返回值的方式传递 char * Getmemory(int n)
# include # include char * Getmemory(int);int main(){char *p = NULL;int n = 10;p = Getmemory(n);if(p == NULL){    return -1;}printf("%d\n",p);for(int i=0;i

但用这种方法需要考虑到return的应该为动态内存的地址而不能使静态内存的地址。

二、错误的跨函数使用malloc的方法
1.char* Getmemory(void)
# include # include char * Getmemory(void);int main(){char *p = NULL;p = Getmemory();printf("%d,%s\n",p,p);free(p);p = NULL;return 0;}char * Getmemory(void){char * p = "Hello world";return p;}
函数内部分配的是栈内存,其会随着函数的结束而释放,故本程序会出错。

2. void Getmemory(char* p)
# include # include void Getmemory(char *);int main(){char *p = NULL;int n;Getmemory(p,n);printf("%d,%s\n",p,p);free(p);p = NULL;return 0;}void Getmemory(char *p,int n){p = (char*)malloc(n*sizeof(char));}
函数形参传递的是数值,而且是无法返回动态分配的内存。


原创粉丝点击