简体   繁体   English

为什么静态变量的溢出会导致段错误,而不是全局变量?

[英]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). 起初,我认为这是因为它们的存储位置,但它们都位于bss区域(全局和未初始化)。 From what I understood and read here on Stackoverflow, all static does is make the variable limited to an internal linkage but nothing else. 根据我对Stackoverflow的了解和阅读,所有静态操作都是将变量限制为内部链接,而没有其他操作。

(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: 每当您越过数组的已定义限制的边界(无论是静态还是全局)时,C中就不会进行数组边界检查,因此,您可能会或可能不会遇到运行时违规,运气因素就在此in。您需要分配额外的空间,包括字符串null终止符:

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. 基本上,两个代码段中的内容都是Array ofboundbound access ,这将导致未定义的行为。 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. 由于未定义行为,因此可能会发生任何事情,在您的情况下,您很幸运,没有看到崩溃(第一个代码段),但您永远不能依靠它。

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

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