每日一题(20)——malloc与free(一)

来源:互联网 发布:网络日报 编辑:程序博客网 时间:2024/06/01 12:48

void GetMemory(char *p){  p = (char *)malloc(100);} void Test(void){  char *str = NULL;    GetMemory(str);    strcpy(str, "hello world");    printf(str);}

1、指出编程错误

2、指出错误后果

3、指出纠正方法






分析:

1、调用GetMemory( str )后, str并未产生变化,依然是NULL.只是改变的str的一个拷贝的内存的变化

2、strcpy( str, "hello world" );程序运行到这将产生错误。

3、推荐使用2级指针形式,如下:

void GetMemory(char **p, int num){    *p = (char *)malloc(sizeof(char) * num);}void Test(void){    char *str=NULL;    GetMemory(&str, 100);    strcpy(str,"hello world");    printf(str);    free(str);    str=NULL;}






原创粉丝点击