重用 malloc 将不同的指针传递给信号处理程序

发布于 2024-11-06 08:24:33 字数 804 浏览 1 评论 0原文

在下面的代码块中,我创建了一个指向结构的指针,以便可以向 gtk 信号处理程序提供多个变量,该处理程序被设置为在处理程序断开连接时自动 g_free() 该结构。

第二部分再次malloc该变量并将新指针发送到新信号处理程序。这行得通吗?

仅通过阅读它,我认为它将把第一个结构数据保留在指针处,并创建一个新指针,我可以稍后更改数据,同时稍后正确处理内存。

知道 malloc 并不是那么简单,我想知道是否有一些我遗漏的东西,或者应该考虑到的东西。

signaldata * s;
s = (signaldata *) g_malloc(sizeof(signaldata *));
s->col = 0; s->secondaryCol = -1; s->model = GTK_TREE_MODEL(itemModel);
g_signal_connect_data(firstWidget,"edited",(GCallback) treeview_text_edited,s, (GClosureNotify) g_free, 0);

s = (signaldata *) g_malloc(sizeof(signaldata *));
s->col = 1; s->secondaryCol = -1; s->model = GTK_TREE_MODEL(itemModel);
g_signal_connect_data(secondWidget,"edited",(GCallback) treeview_text_edited,s, (GClosureNotify) g_free, 0);

In the following code block, I create a pointer to a struct so I can supply multiple variables to a gtk signal handler, which is set to automatically g_free() the struct when the handler is disconnected.

The second part mallocs the variable again and sends the new pointer to the new signal handler. Will this work?

Just from reading it I presume it will leave the first struct data in place at the pointer, and create a new pointer I can change the data in later, all while properly disposing of the memory later.

Knowing that malloc is hardly so simple, I'm wondering if there is something I'm missing, or should take into account.

signaldata * s;
s = (signaldata *) g_malloc(sizeof(signaldata *));
s->col = 0; s->secondaryCol = -1; s->model = GTK_TREE_MODEL(itemModel);
g_signal_connect_data(firstWidget,"edited",(GCallback) treeview_text_edited,s, (GClosureNotify) g_free, 0);

s = (signaldata *) g_malloc(sizeof(signaldata *));
s->col = 1; s->secondaryCol = -1; s->model = GTK_TREE_MODEL(itemModel);
g_signal_connect_data(secondWidget,"edited",(GCallback) treeview_text_edited,s, (GClosureNotify) g_free, 0);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

似狗非友 2024-11-13 08:24:33

应该没问题,因为指针本身是在调用 g_signal_connect_data 之前复制的,因此稍后通过执行第二次 g_malloc 为其分配新地址并不重要。

但是,您会丢失对第一个 g_malloc 内存的唯一引用(除非以某种方式可以从 firstWidget 访问它),如果您想做任何进一步的手动操作,这可能是不可取的对其进行操纵。

It should be OK because the pointer itself is copied before calling g_signal_connect_data, so it doesn't matter that later you assign it a new address by doing a second g_malloc.

However, you lose your only reference to the first g_malloc'd memory (unless somehow it becomes accessible from firstWidget) and that can be undesirable if you want to do any further manual manipulation to it.

﹂绝世的画 2024-11-13 08:24:33

如果从不使用该信号,看起来就会出现内存泄漏。

这对您来说可能是问题,也可能不是问题。

It looks like there will be a memory leak if the signal is never used.

That may or may not be a problem for you.

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