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 segmentation 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;
}
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.