内存管理

来源:互联网 发布:被淘宝卖家骚扰怎么办 编辑:程序博客网 时间:2024/06/08 10:33

判断这段程序,它的问题有哪些?

#include <stdio.h>#include <string.h>#include <stdlib.h>void getmemory(char *p){p = (char *)malloc(100);}int main(void){char *str = NULL;getmemory(str);strcpy(str,"hello world!");printf("%s",str );}

这段程序执行之后会发生段错误,原因就是在调用函数getmemory时,传递的是指针str的形参,所以在函数调用结束后,str最终还是指向的NULL,并没有给str分配到实际的内存空间来让它存储数据。

如果将程序修改为下面这样,则能成功输出str的内容,打印"hello world!"语句。

#include <stdio.h>#include <string.h>#include <stdlib.h>void getmemory(char **p){*p = (char *)malloc(100);}int main(void){char *str = NULL;getmemory(&str);strcpy(str,"hello world!");printf("%s\n",str );}
在调用函数getmemory时,传递str的地址给函数的参数,函数形参使用二级指针,则对*p分配内存空间时,就相当于对str指针分配了内存空间,使str指向了一段长度为100的char型空间。

原创粉丝点击