[英]If a static variable is declared out side of a function, will the memory address be the same as if it's declared in a function
I was asked these 2 questions during an interview.我在面试的时候被问到这两个问题。 I guess the address of a static variable will be the same no matter where it is declared.
我猜 static 变量的地址将是相同的,无论它在哪里声明。 It will also have the same address from run to run.
从运行到运行,它也将具有相同的地址。 Correct me if I am wrong.
如果我错了,请纠正我。
If a static variable is declared out side of a function, will the memory address be the same as if it's declared in a function? If a static variable is declared out side of a function, will the memory address be the same as if it's declared in a function?
If a static variable is declared out side of a function, will it have the same address every time you run the program?如果 static 变量在 function 之外声明,那么每次运行程序时它是否具有相同的地址?
Cunningham's Law will ensure quick correction of my mistakes:坎宁安定律将确保快速纠正我的错误:
#include <stdio.h>
#ifdef GLOBAL
static int i;
#endif
// static int j;
#ifndef GLOBAL
void f(void) {
static int i;
printf("local: %p\n" , (void *) &i);
}
#endif
int main() {
#ifdef GLOBAL
printf("global: %p\n" , (void *) &i);
#else
f();
#endif
}
You need to disable address randomization to observe it:您需要禁用地址随机化来观察它:
$ sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space';\
gcc 1.c && ./a.out &&\
gcc -DGLOBAL 1.c && ./a.out;\
sudo bash -c 'echo 2 > /proc/sys/kernel/randomize_va_space'
local: 0x555555558034
global: 0x555555558034
If you add another global static int j
(commented out above) after the global i
then the effect goes away:如果在全局
i
之后添加另一个全局static int j
(上面注释掉),那么效果就会消失:
local: 0x555555558038
global: 0x555555558034
So call me maybe ??所以打电话给我吧??
$ ./a.out && ./a.out
global: 0x563bcce14034
global: 0x55cd4a497034
static
variables may or may not have the same address in memory when declared globally or locally in the body of a function.当在 function 的主体中全局或局部声明时,
static
变量在 memory 中可能具有相同的地址,也可能不同。 The fact is nothing can be assumed about these addresses: the C Standard only guarantees that they compare different from the null pointer and different from the addresses of other data objects defined in a C module (albeit compiler extensions can force some symbols to alias one another).事实上,对于这些地址没有任何假设:C 标准仅保证它们比较不同于 null 指针,并且不同于在 Z0D61F8370CAD1D412F80B84D143E125 中定义的其他数据对象的地址(可以强制某些符号为另一个编译器模块扩展名) )。
Modern operating systems use address randomisation to make it more difficult for attackers to exploit software flaws, so the addresses may indeed differ from one run to another.现代操作系统使用地址随机化使攻击者更难利用软件缺陷,因此地址可能确实会因运行而异。
Answering such questions in an interview is tricky: the interviewer's assumptions might be outdated, but a substantiated answer should get you a good mark.在面试中回答这样的问题是很棘手的:面试官的假设可能已经过时,但一个有根据的答案应该会给你一个好分数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.