C替代malloc

Ser*_*kov 0 c malloc struct pointers

在阅读K&R(第6.5节,第二版)时,我遇到了以下功能:

struct tnode *talloc(void)
{
    return (struct tnode *) malloc( sizeof(struct tnode) );
}
Run Code Online (Sandbox Code Playgroud)

该函数分配一些空格来存储struct tnode.我只是想通过询问我是否会达到以下目的来检查我的理解:

struct tnode *talloc(void)
{
    struct tnode s;
    return &s;
}
Run Code Online (Sandbox Code Playgroud)

MrT*_*Tux 9

答案是不.

struct tnode *talloc(void)
{
    return (strcut tnode *) malloc( sizeof(strcut tnode) );
}
Run Code Online (Sandbox Code Playgroud)

malloc分配可以在之后使用的空间,通常是在堆上分配空间.分配的空间malloc需要在您不再需要时手动免费 - 否则您将获得内存泄漏.返回函数后可以使用此指针.

在以下示例中

strcut tnode *talloc(void)
{
    struct tnode s;
    return &s;
}
Run Code Online (Sandbox Code Playgroud)

结构在堆栈上分配,并在函数退出时自动释放.因此,您返回的指针变为悬挂指针,您无法使用(在函数外部).在其作用域之外使用作用域对象是未定义的行为.