-1
这里是我的代码是否通过的malloc分配的内存有边界?
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
int main()
{
void *p=malloc(1);
int *x=(int*)(p);
*(x+1000)=1000;
printf("*(x+1000)=%d\n",*(x+1000));
//*(x-100)=-100;
//Segmentation fault
return 0;
}
输出
*(x+1000)=1000
,但我没跟4000(1000 *的sizeof(INT分配的内存) )大小内存,只有1.
当我用*(x-100)=-100
时,shell会输出Segmentation fault
,这似乎是有道理的。
你能告诉我为什么吗?
感谢
我使用Ubuntu 16.04.4和gcc 5.4.0
未定义的行为未定义。 – John3136