简体   繁体   English

C语言中的简单堆栈损坏

[英]Simple stack corruption in C

Can somebody explain me, why in this program if I call the printf in that way the flag will be win? 有人可以解释一下,如果在该程序中以这种方式调用printf ,为什么标志会赢? but without will not? 但是没有会不会? Why this printf allow such things i can't understand thanks. 为什么这个printf允许这样的事情我不明白,谢谢。 Why without the printf the array can't overwrite the variable flag? 为什么没有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;
}

Your program acesses the array beyond it's bounds. 您的程序访问数组超出范围。 The array indexes start at 0 and end at N - 1 where N is the size of the array. 数组索引从0开始,到N-1结束,其中N是数组的大小。

Doing this invokes undefined behavior, so your prediction of program's behavior will be wrong after this. 这样做会调用未定义的行为,因此此后您对程序行为的预测将是错误的。 Adding the printf() can change this behavior and it does, and that is what undefined behavior means, it should not affect the behavior of the program but once you have caused the undefined behavior at 添加printf()可以更改此行为,并且确实可以做到这一点,这就是未定义行为的含义,它不应影响程序的行为,但是一旦在以下位置导致了未定义行为,

arr[10] = 1;

you cannot know how the program will behave anymore. 您不知道该程序将如何运行。

This is causing your problem 这是造成您的问题

arr[10] = 1;

You only allocate 10 elements in your array 您只能在数组中分配10个元素

int arr[10] = { 0 };

arr[10] is actually trying to access the 11th element in the array because array indices start at 0 . arr[10]实际上试图访问数组中的第11个元素,因为数组索引从0开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM