函数的局部静态变量
在 Linux 中,“静态”变量存在于 BSS 段中(在未运行的代码中),“局部”变量存在于“堆栈”中。 这意味着函数本地的静态变量存在于 BSS 区域中。如何记账以确保范围在函数本身之内?
In Linux, "static" variables are present in the BSS segment (in a code that is not running) and "local" variables are present in the "stack".
This means that static variables local to a function are present in the BSS area. How is the book-keeping done to ensure that the scope is within the function itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

变量的存储位置与作用域无关。通常是编译器本身限制范围(对变量的访问)。当您有这样的语句时:
在函数内,将不允许该函数外部的代码访问 xyzzy,无论它是否具有静态存储持续时间。
任何这样做的尝试都将是编译时错误,而不是运行时检查。
事实上,您可以影响局部静态变量,但可以通过缓冲区溢出(运行到它所在的存储区域)之类的方式来影响,而不是通过其名称(编译器将不允许这样做)。
Where a variable is stored has nothing to do with scope. It's usually the compiler itself that restricts scope (access to the variable). When you have a statement like:
within a function,
xyzzy
will not be allowed to be accessed by code outside that function, regardless of the fact that it has static storage duration.Any attempt to do so will be a compile-time error, not a run-time check.
In fact, you can affect the local static variable but with something like a buffer overflow (running into the storage area where it exists), not via its name (which the compiler will disallow).