考虑以下两个程序:
/***************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;
}
你能解释为什么第一个有效,而第二个无效吗?
最佳答案
“正确”工作的代码有 undefined behavior .这只是(坏)运气,它起作用了。实际上似乎有效是 UB 可能发生的最坏结果(不会引起您的警报)。其他不起作用的代码也有未定义的行为。
您可以在 malloc
、realloc
返回的指针上调用 free
only或 calloc
关于c - 免费提供错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6610178/