每日一题(23)——malloc与free(四)

xiaoxiao2021-02-28  106

void Test(void) { char *str = (char *)malloc(100); strcpy(str, "hello"); free(str); if(str != NULL) { strcpy(str, "world"); printf(str); } } 1、指出编程错误 2、指出错误后果

3、指出纠正方法

分析:

    篡改动态内存区的内容,后果难以预料,非常危险;因为free(str)之后,str成为野指针,

    if(str != NULL)语句不起作用;

    将free(str);放在Test最后,处理完成之后再释放。

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

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

最新回复(0)