静态全局变量与全局变量C [英] Static global variables vs global variables C

查看:149
本文介绍了静态全局变量与全局变量C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的程序.如果我将变量a,b,c声明为静态全局变量,则会出现分段错误,但是如果我将其声明为非静态全局变量或作为局部变量,则不会出现分段错误.为什么会这样表现?我知道数据存储的量超过了变量,但是为什么当仅声明为静态时,它会产生段错误?是否将静态声明的变量存储在堆栈框架的某些不允许覆盖的不同部分中?

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?

我知道strcpy不安全.但这不是我的问题.我想了解为什么一个溢出会产生段错误,为什么另一个溢出可能不会产生段错误.

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

推荐答案

内存对齐在堆栈变量中很重要. 尝试使用-fstack-protector-strong或类似的堆栈保护选项,您将看到崩溃. 在c之后还声明一个int并使数组c溢出,可以看到崩溃. 您需要确保没有填充. 由于b是一个数组,因此从'a'溢出的所有内容都将进入b. 尝试类似的东西:

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));

当您溢出c时,您将看到崩溃.

you will see the crash when you overflow c.

溢出时,您遇到未定义的行为.

You are hitting undefined behaviour when you overflow.

这篇关于静态全局变量与全局变量C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆