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

xiaoxiao2021-02-28  94

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; }

转载请注明原文地址: https://www.6miu.com/read-64505.html

最新回复(0)