找到你要的答案

Q:Saving alphabet in array gets stack smashing error

Q:保存数组中的字母得到堆栈错误

This is a little simple program to save and show all the ASCII alphabet letters in an array:

#include <stdio.h>

int main(void) {

        int j = 0;
        char alpha[52];

        for (i=65;i<=122;i++) {
                if (i<=90 || i>=97) {
                        alpha[j] = i;
                }
                j++;
        }

        printf("\n");
        return 0;
}

It gets the following error:

*** stack smashing detected ***: ./program.c terminated
Canceled (Created core dump)

What's wrong with that code?

这是一个很小的简单的程序来保存和显示所有的ASCII字母数组:

#include <stdio.h>

int main(void) {

        int j = 0;
        char alpha[52];

        for (i=65;i<=122;i++) {
                if (i<=90 || i>=97) {
                        alpha[j] = i;
                }
                j++;
        }

        printf("\n");
        return 0;
}

它得到以下错误:

*** stack smashing detected ***: ./program.c terminated
Canceled (Created core dump)

那个代码怎么了?

answer1: 回答1:

The problem is simply that the array alpha is created to be of size 52 elements but you are inserting past the end of that last element in your loop because you increment your array index variable j outside of the if statement. Move the j increment code inside your if block when you add an element to the array like this

for (i=65;i<=122;i++) 
{
    if (i<=90 || i>=97) 
    {
        alpha[j] = i;
        j++;  /* place the increment here */
    }
    /* instead of here */
}

This ensures that you only increment j when you are actually writing to the array. Failing to do this results in j becoming larger than 51 which is the highest index you can write to without going past the array end.

Your code as it stands allows j to exceed 51 and at this point the value of i is also in such a range that your if condition is satisfied - so you write to alpha[j] and writing past array bounds results in undefined behaviour.

If you had used a debugger this would be been obvious from the start.

问题是,数组alpha被创建为大小为52的元素,但是你插入了循环中最后一个元素的结尾,因为在if语句之外增加了数组下标变量j。当你向数组中添加一个元素时,请在if块中移动J增量代码

for (i=65;i<=122;i++) 
{
    if (i<=90 || i>=97) 
    {
        alpha[j] = i;
        j++;  /* place the increment here */
    }
    /* instead of here */
}

这样可以确保当实际写入数组时只增加j。没有做到这一点导致J变大超过51,这是最高的索引,你可以写到不经过数组结束。

您的代码,因为它的立场允许J超过51,在这一点上,我的价值也在这样的范围内,如果你的条件是满意的-所以你写的阿尔法J和写过去的数组边界结果在未定义的行为。

如果您使用了调试器,这将是显而易见的,从一开始。

c  char  ascii