【发布时间】:2020-01-02 20:29:35
【问题描述】:
这是我大学的练习。目标是进行非法内存存储和非法内存访问,并将其打印在 char 中。但是,使用 MALLOC 的内存地址不存储 'y',并且使用 char x 有效。 为什么会有这种差异?但是当我使用 char x 时,它会显示我想要的内容,但是,最后会显示此文本“* stack smashing detected *: terminate Abortado (imagem do núcleo gravada)"
void ilegal_store(char *u)
{
for(int i=0;i<100;i++){
*(u+i) = 'y';
}
}
void ilegal_reading(char *u)
{
for(int i=0;i<100;i++){
printf("%d = %d\n",i,*(u+i));
}
}
void main()
{
//char x; WORKS
char *x=(char *)malloc(sizeof(char)); //USING MALLOC HAS ADRESSES WHICH DOESN'T STORE THE 'y' by ilegal_store();
if(x!=NULL){
ilegal_store(x); //use &x when not pointer
ilegal_reading(x); //use &x when not pointer
}
}
【问题讨论】:
-
你说“不起作用”是什么意思?如果您正在访问数组之外的内存,则代码具有未定义的行为。
-
好的,谢谢。我知道这一点,我希望这种非法访问可以更好地理解 C。如果我使用 (printf("\n%d = %c", *(p+i), *(p+i))跨度>
-
假设没有 UB,
printf正在缓冲其输出(并且可能仅在打印换行符时刷新它)。尝试在printf之后添加fflush(stdout)。 -
“不起作用”不是对您的问题的非常有用的描述。请始终包括您期望的输出、获得的输出以及提供的输入。当你的程序“不工作”时,你的程序会做什么?
-
@BrendonRusPeres 如果我们还没有将您赶走,请尝试 mosvy 的建议,并在您的 printf 后添加
fflush(stdout)和%c。很有可能这就是问题所在。
标签: c