struct (stack overflow)

First, let's look at a piece of code:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int a[2];
    double d;
} struct_t;    //定义一个结构体,注意此时结构体内的数组在数值之前,且数组只能存储两个数

double fun(int i) {
    volatile struct_t s;
    s.d = 3.14;     //将d初始化为3.14
    s.a[i] = 1073741824; /* Possibly out of bounds */
    return s.d; /* Should be 3.14 */
}

int main(int argc, char *argv[]) {
    int i = 0;
    if (argc >= 2)
    i = atoi(argv[1]);
    double d = fun(i);
    printf("fun(%d) --> %.10f\n", i, d);
    return 0;
}

Let's look at the results of the operation below:
Insert picture description here
we can see that since the array (sequential storage) in the structure contains at most two numbers, its subscript should be 0 or 1. When we input parameter 1, 3.14 is displayed normally Comes out, but when we enter 2, our access to the previous array is out of range. 3.14 is displayed as 3.1399998665. When the input number is 3, the error is even more outrageous. But 4 and 5 are displayed normally again. This is because the address we visited has already passed the storage address of 3.14, so the output is not affected. My computer displays "core dumped" when I input 6, but some computers can continue to run, depending on the computer.
This is an error caused by out-of-bounds access.

Guess you like

Origin blog.csdn.net/xiongdan626/article/details/90574716