-2
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
main()
{
int *ptr,i;
ptr=(int*)malloc(sizeof(int));
printf("sizo of ptr is:%d",sizeof(ptr));
for(i=0;i<30;i++)
scanf("%d",ptr+i);
for(i=0;i<30;i++)
printf("%d",*(ptr+i));
getch();
}
這裏ptr的大小是:4 我的問題是,我想在ptr中只存儲一個整數,但在這個程序中我可以存儲超過30或100等,爲什麼它不會拋出錯誤?malloc真正分配多少內存?
因爲今天你有一些運氣。它可能會在明天崩潰。 – jweyrich 2014-09-04 13:31:29
我在linux和windows中檢查過這個程序。兩者都給出了相同的結果。目前我正在使用dev C++。 – user3614789 2014-09-04 13:34:38
相關的問題,關於溢出堆棧上的緩衝區(相同的一般答案):http://stackoverflow.com/questions/23226217/why-buffer-overflow-doesnt-affect-to-this-code – 2014-09-04 13:45:38