重用 malloc 将不同的指针传递给信号处理程序
在下面的代码块中,我创建了一个指向结构的指针,以便可以向 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 malloc
s 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该没问题,因为指针本身是在调用 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 secondg_malloc
.However, you lose your only reference to the first
g_malloc
'd memory (unless somehow it becomes accessible fromfirstWidget
) and that can be undesirable if you want to do any further manual manipulation to it.如果从不使用该信号,看起来就会出现内存泄漏。
这对您来说可能是问题,也可能不是问题。
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.