释放 C 结构体的字符串成员
我的结构如下:
struct something{
char *string_member;
};
现在我创建了
struct something *s = malloc(sizeof(struct something));
s.string_member = malloc(5); //one way
s.string_member = "some thing wrong"; // second way
当我释放 s 指向的内存时。在这两种情况下如何释放分配给 string_member 的内存。我是否需要担心第二种情况下的 string_member ?
I have a structure as follows:
struct something{
char *string_member;
};
now I created
struct something *s = malloc(sizeof(struct something));
s.string_member = malloc(5); //one way
s.string_member = "some thing wrong"; // second way
While I free the memory pointed by s. How do I free the memory allocated to string_member in the both the cases. Do I have to worry about string_member in second case at all?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在
第二种方式
示例中释放它,并且您无法仅通过查看指针来(可移植地)区分情况一和情况二。因此,不要这样做,请确保始终使用malloc
或例如strdup
分配string_member
。这样,您就可以随时释放
它(一次)。You mustn't free it in your
second way
example, and you have no way to (portably) make the difference between case one and case two by just looking at the pointer. So don't do that, make sure you always allocate thestring_member
usingmalloc
or e.g.strdup
. That way, you can alwaysfree
it (once).在第一种情况下,调用
free(s.string_member)
。在第二种情况下,您无需执行任何操作。这是因为该字符串不是动态分配的。它所在的位置是在加载程序时确定的,并且对其进行的任何清理也是由系统完成的。In the first case, call
free(s.string_member)
. In the second case, you don't have to do anything. This is because the string is not dynamically allocated. The location where is resides is determined when the program is loaded, and any cleaning up for it is also done by the system.