函数中结构指针的范围 [英] scope of struct pointers in functions

查看:115
本文介绍了函数中结构指针的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在函数中具有以下内容:

struct example *A=malloc(sizeof(struct example));

在函数结束/离开之后,是否在A指向的节点上创建了要破坏的节点/内存空间?还是留在堆里?

解决方案

您必须free malloc的所有内容.当函数返回时,变量A超出范围,但内存保持分配状态.当您丢失了指向内存的指针(除非存储在其他位置)时,您就是泄漏内存.

如果仍然需要A指向的内存,则可以将指针返回到分配的结构,并在以后释放它.如果函数返回后不需要分配的内存,请使用free(A)释放内存.

If i have the following in a function:

struct example *A=malloc(sizeof(struct example));

does the node/memory space created where A points to get destroyed after the function ends/leaves? Or does it stay in the heap?

解决方案

You have to free everything that you malloc. When your function returns, the variable A goes out of scope, but your memory stays allocated. As you have lost the pointer to the memory (unless stored elsewhere) you are leaking memory.

If you still need the memory pointed to by A, you could return the pointer to the allocated struct, and free it later. If you don't need the allocated memory once your function returns, free the memory with free(A).

这篇关于函数中结构指针的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆