Static global variables vs global variables C

孤者浪人 提交于 2019-12-11 10:36:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!