就业数据资源平台
当前位置:首页 > 笔试题目
笔试题(GetMemory)


void GetMemory2(char **p, int num)


{


p = (char *)malloc(num);

}


void Test(void)


{


char *str = NULL;


GetMemory(&str, 100);


strcpy(str, "hello");


printf(str);


}


请问运行Test函数会有什么样的结果?


答:


(1)能够输出hello (2 )Test函数中也未对malloc的内存进行释放。(3)GetMemory避免了试题1的问题,传入GetMemory的参数为字符串指针的指针,但是在GetMemory中执行申请内存及赋值语句


p = (char *) malloc( num );

后未判断内存是否申请成功,应加上: if ( *p == NULL ) {


    ...//进行申请内存失败处理

 }


 


void Test(void)


{


char *str = (char *) malloc(100);


     strcpy(str, “hello”);

     free(str);     

     if(str != NULL)

     {

       strcpy(str, “world”);

printf(str);


}


}


请问运行Test函数会有什么样的结果?


答:执行 char *str = (char *) malloc(100); 后未进行内存是否申请成功的判断;另外,在free(str)后未置str为空,导致可能变成一个“野”指针,应加上: str = NULL;

 


就业数据资源平台