3

c语言中的全局变量和堆变量有什么区别和相似之处?

假设我有这段代码。

const char* globalVar = "This is a string";

int main(int argc, char* argv[]){
    char* heapVar = malloc(7 * sizeof(char));
}

那么 globalVar 和 heapVar 有什么区别和相似之处呢?

提前致谢。

4

3 回答 3

2

Global variables and heap variables are two different concepts. A heap variable simply tells you where space for the variable was allocated, while a global variable tells you the scope of the variable.

Global means the variable is visible to anything, and it is opposed to local which means a variable's visibility is restricted.

Heap means the variable (pointer) was dynamically allocated (eg: with malloc), and is opposed to stack where the variable was not dynamically allocated.

So you can have a global heap variable, a global stack variable, a local heap variable or a local stack variable.

In your case, globalVar is global because it is declared outside of the scope (braces) of any function, while heapVar is local to main. heapVar is declared on the heap because of the call to malloc. globalVar is a special case because it's using a char* declaration.

For more details on how char* style declarations are handled, please see: Heap or Stack? When a constant string is referred in function call in C++

于 2012-12-26T14:03:34.677 回答
0

全局变量始终存在,它永远不会消失。此外,它在该文件/模块中的所有函数中都是可见的,除非声明为“静态”,否则它在整个文件/模块中也是可见的。

请注意,您的全局变量不是“这是一个字符串”,而只是那个 globalVariable,它只是一个指针(包含内存中的地址)。

heapVar 变量包含指向堆上某物的地址。该变量仅在 main() 函数内可见。

可以使全局变量指向堆。

这里的区别是 globalVariable 指向的内容是静态分配的,而 heapVar 指向的内容是动态分配的(你可以通过调用 free() 和释放内存来销毁它,而你不能释放那个字符串“This is a string”,即 globalVar 指向的内容)。

于 2012-12-26T14:05:46.940 回答
0

注意:这里我谈论的是 globarVar 和 heapVar,而不是他们指向的内存。
区别在于:

范围

heapVar 在 stack 中,而不是在 heap中,因此它的作用域是其函数的本地范围,并且 globarVar 在任何地方都可以评估。

人生

heapVar 在函数调用结束时死亡, globarVar 在程序的所有持续时间内都存在。

关于他们指向的内存:

heapVar 指向的内存在堆中,而 globarVar 指向的内存在实现定义的只读内存中,为了安全,将其设为 const char*:

char* globalVar = "This is a string";

堆中的内存可以随时释放,文字字符串在程序的所有持续时间内都存在。在您的情况下,您有泄漏。无论如何,我知道这只是一个示例,也许您已经意识到了。

于 2012-12-26T14:27:21.237 回答