C常错题目
找错
1,
void GetMemory( char *p ) { p = (char *) malloc( 100 ); } void Test( void ) { char *str = NULL; GetMemory( str ); strcpy( str, "hello world" ); printf( str ); }
因为str是指针,GetMemory的形参应为双重指针 void GetMemory(char **p), malloc可能申请空间失败 ,应在后面加 if(str == null)( ... 失败处理方法 ...).
2,
char *GetMemory( void ) { char p[] = "hello world"; return p; } void Test( void ) { char *str = NULL; str = GetMemory(); printf( str ); }
p为局部变量,调用完GetMemory(),后p会消失; 所以 p 要修改为 static ;
3,
void Test( void ) { char *str = (char *) malloc( 100 ); strcpy( str, "hello" ); free( str ); //省略的其它语句 }
malloc可能申请空间失败 ,应在后面加 if(str == null)( ... 失败处理方法 ...). free(str)后, str变为野指针,应加上 str = null;

浙公网安备 33010602011771号