免费提供错误

arp*_*ita 0 c unix malloc

考虑以下两个程序:

/***************correct: no error for this code **************/
#include <stdio.h>
#include <string.h>
int main()
{

char  *p ,*q ;
p =(char *)malloc(10) ;
 strcpy( p , "AB") ;
*p = '\0' ;
p++ ;
q = p ;
//*q = 32 ;
free(q) ;
return 0;
}
/*************code2 which gives error ********************/
#include <stdio.h>
#include <string.h>
int main()
{

int  *p ,*q ;
p =(int  *)malloc(10) ;
*p = 30 ;
p++ ;
q = p ;
*q = 32 ;
free(q) ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

你能解释为什么第一个有效,但第二个没有?

Arm*_*yan 13

工作"正确"的代码具有未定义的行为.它的运气只是(坏)运气.实际上看起来工作是由于UB可能发生的最坏情况(不会引起警报).其他不起作用的代码也有未定义的行为.

您可以free 调用返回的指针malloc,realloccalloc