问题
I have the program below. If i declare variables a,b,c static global variables, it gives segmentation fault, but if i declare them non-static global or as local variables, it won't give segmentation fault. Why does it behave in such a way? I know that there is more data than variables can store, but why does it give seg fault when only its declared static? Are statically declared variables stored in some different part of the the stack frame where overwriting is not allowed?
EDIT: I know strcpy is not safe. But that is not my problem. I want to understand why one overflow gives segfault, why the other overflow might not give segfault.
#include<stdio.h>
#include<string.h>
static char a[16];
static char b[16];
static char c[32];
int main(int argc, char *argv[]){
// char a[16];
//char b[16];
//char c[32];
strcpy(a,"0123456789abcdef");
strcpy(b,"0123456789abcdef");
strcpy(c,a);
strcpy(c,b);
printf("a = %s\n",a);
return 0;
}
回答1:
memory alignment matters in stack variable. Try it with -fstack-protector-strong or similar stack protection option you will see the crash. Also declare an int after c and overflow your array c, you can see the crash. you need to make sure that there is no padding. since b is an array, whatever you overflow from 'a' goes to b. Try something like:
struct foo {
char c[10];
int x;
} __attribute__((packed));
you will see the crash when you overflow c.
You are hitting undefined behaviour when you overflow.
回答2:
Careful that const char* string in C are always 0-terminated, meaning that the string "0123456789abcdef" is actually 17 characters: "0123456789abcdef\0"
I suggest you to use always the secure version
strncpy()
You can also have a look at the documentation which tells you explicitly that the null character is included.
http://www.cplusplus.com/reference/cstring/strcpy/
来源:https://stackoverflow.com/questions/29501783/static-global-variables-vs-global-variables-c