简体   繁体   中英

Saving alphabet in array gets stack smashing error

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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