简体   繁体   中英

Why does an overflow in a static variable cause seg fault but not global variables?

Why does the code fail with a segmentation fault for the first set of code but the second block doesn't? (Only difference is that the chars are static in the first but not static in the second).

#include <string.h> 
#include <stdio.h>
static char a[16];
static char b[16];
static char c[32];
int main(int argc, char *argv[]) {
    strcpy(a, "0123456789abcdef");
    strcpy(b, "0123456789abcdef");
    strcpy(c, a);
    strcat(c, b); 
    printf("a = %s\n", a);
    return 0;
}

.

#include <string.h> 
#include <stdio.h>
char a[16];
char b[16];
char c[32];
int main(int argc, char *argv[]) {
    strcpy(a, "0123456789abcdef");
    strcpy(b, "0123456789abcdef");
    strcpy(c, a);
    strcat(c, b); 
    printf("a = %s\n", a);
    return 0;
}

At first I thought it's because of where they are stored but they are both in the bss region (both global and uninitialized). From what I understood and read here on Stackoverflow, all static does is make the variable limited to an internal linkage but nothing else.

(I know that there is no space allocated for the null character. This behavior is consistent).

Just because of luck. Whenever, you cross the boundary of the defined limit of an array (be it static or just global, whatever), there is no array boundary check in C, as such, you may or may not get runtime violations, where the luck factor comes in. You need to allocate extra space including the string null terminator:

char a[16+1];
char b[16+1];
char c[32+1];

Basically what you have in both the code snippet is Array out of bound access and this will lead to undefined behavior. So there are chances that the first code snippet might crash on some other system. Since the behavior is not defined anything might happen and in your case you are lucky and don't see a crash(1st code snippet) but you can never rely on this.

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