C中的简单堆栈损坏

时间:2018-03-20 23:32:37

标签: c stack buffer-overflow

有人可以解释一下,为什么在这个程序中,如果我以这种方式调用printf,那么旗帜将会获胜?但没有不会?为什么这个printf允许这样的事情我无法理解谢谢。为什么没有printf数组不能覆盖变量标志?

#include <stdio.h>
#include <stdbool.h>

int main() {

    int flag = false;

    int arr[10] = {0};
    int siz = sizeof(arr) / sizeof(* arr);

    printf("%p", &flag);
    arr[10] = 1; // Without the printf call can't get the win. Why?
    puts("");

    if(flag == true)
    {
        printf("win !");
    }
    else
    {
        printf("lose");
    }



    return 0;
}

2 个答案:

答案 0 :(得分:4)

你的程序超越了它的范围。数组索引从 0 开始,到 N - 1 结束,其中 N 是数组的大小。

执行此操作会调用未定义的行为,因此在此之后您对程序行为的预测将是错误的。添加arr[10] = 1; 可以改变这种行为,而且确实如此,这就是未定义的行为意味着,它不应该影响程序的行为,但是一旦你在中导致了未定义的行为p>

RenderTargetBitmap

你不知道程序将如何表现。

答案 1 :(得分:0)

这导致了您的问题

S

您只在阵列中分配10个元素

arr[10] = 1;

int arr[10] = { 0 }; 实际上是在尝试访问数组中的第11个元素,因为数组索引从arr[10]开始。

相关问题