简体   繁体   English

堆栈结构与堆结构有什么区别?

[英]What is the difference between stack struct vs heap struct?

// Define Person 
typedef struct Person {
    char *name;
    int age;
} person_t;

// Init person in heap
person_t *create_person_v1(char *name, int age)
{
    person_t *person = calloc(1, sizeof(person_t));
    person->name = name;
    person->age = age;
    return person;
}

// Init person on stak? a static struct I guess?
person_t create_person_v2(char *name, int age)
{
    return (person_t) {name, age};
} 

The code above has a definition of Person and two helper functions for its further initialization.上面的代码有一个 Person 的定义和两个用于进一步初始化的辅助函数。

I don't really understand the difference between them, and what are the benefits of having each?我真的不明白它们之间的区别,拥有它们有什么好处

Is it something more than just accessors -> and .它不仅仅是访问器->. ? ?

The last function does not allocate a static structure, but a structure on the stack.最后一个函数不分配静态结构,而是分配堆栈上的结构。 There is two kind of memory for your programm, heap and stack.您的程序有两种内存,堆和堆栈。 static is an other keyword (which have more than 1 use, depending on where they are used, but it's not the current subject). static 是另一个关键字(使用次数超过 1 次,具体取决于使用位置,但不是当前主题)。

heap allocations use more ressources than stack allocations, but are not tied to scopes where they are used.堆分配比堆栈分配使用更多的资源,但与使用它们的范围无关。 You can manipulate structures heap allocated between functions without having to think they can be "automatically freed" because the scope on which they are tied disappear (aka : initial function returned).您可以操作在函数之间分配的结构堆,而不必认为它们可以“自动释放”,因为它们绑定的范围消失了(又名:返回的初始函数)。

An example would be a linked list.一个例子是链表。 You can't rely on stack allocations to build a linked list of structures.您不能依赖堆栈分配来构建结构链表。

Heap allocations can fail, you always have to check if malloc, calloc and cie, does not return NULL.堆分配可能会失败,您必须始终检查 malloc、calloc 和 cie 是否不返回 NULL。

Stack allocations doesn't fail like that.堆栈分配不会像那样失败。 If you sucked all your stack, your programm will just crash.如果你吸了所有的堆栈,你的程序就会崩溃。 ( Or do some fancy things, it is undefined bahavior ). (或者做一些花哨的事情,这是未定义的行为)。 But you can't recover from that.但你无法从中恢复。

stack allocated memory is "freed" on function returns.堆栈分配的内存在函数返回时“释放”。 not heap allocated memory.不是堆分配的内存。 But you have to free it by hand (with function free)但是你必须手动释放它(功能免费)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM