释放 C 结构体的字符串成员

发布于 2024-12-12 10:45:30 字数 360 浏览 2 评论 0原文

我的结构如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

百合的盛世恋 2024-12-19 10:45:31

您不能在第二种方式示例中释放它,并且您无法仅通过查看指针来(可移植地)区分情况一和情况二。因此,不要这样做,请确保始终使用 malloc 或例如 strdup 分配 string_member。这样,您就可以随时释放它(一次)。

s.string_member = strdup("some thing wrong");  // the other way

...

free(s.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 the string_member using malloc or e.g. strdup. That way, you can always free it (once).

s.string_member = strdup("some thing wrong");  // the other way

...

free(s.string_member);
清君侧 2024-12-19 10:45:31

在第一种情况下,调用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文