c - 免费提供错误

标签 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;
}

你能解释为什么第一个有效,而第二个无效吗?

最佳答案

“正确”工作的代码有 undefined behavior .这只是(坏)运气,它起作用了。实际上似乎有效是 UB 可能发生的最坏结果(不会引起您的警报)。其他不起作用的代码也有未定义的行为。

您可以在 mallocrealloc 返回的指针上调用 free onlycalloc

关于c - 免费提供错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6610178/

相关文章:

Linux进程显示突然的内存跳转

c - 从字符串中删除多余的空格(就地)

linux - 运行 Logstash.conf 文件时出错

c - memcpy/memset 等可以处理的最大缓冲区大小是多少?

linux - Shell嵌套for循环和字符串比较

c++ - 如何使用 boost 异步执行两个线程?

c++ - 对于具有一维常量的二维数组,使用 delete [] 进行内存释放

algorithm - 计算尺码等级

c - 我正在尝试在 Ubuntu 12.04.1 中进行系统调用。我在编译 hello.c 文件时遇到错误

C 警告 : implicit declaration of function