gpt4 book ai didi

c - 比较已释放的指针会调用 UB 吗?

转载 作者:太空狗 更新时间:2023-10-29 17:01:22 25 4
gpt4 key购买 nike

这似乎是一个相当普遍的模式,例如在 hexchat 中(可能无法编译,另请参阅 plugin docs。另请注意,hexchat_plugin_get_info 尚未永远使用,因此为简单起见,我将其省略):

static hexchat_plugin *ph;
static int timer_cb(void *userdata) {
if (hexchat_set_context(ph, userdata)) { /* <-- is this line UB? */
/* omitted */
}
return 0;
}
static int do_ub(char *word[], char *word_eol[], void *userdata) {
void *context = hexchat_get_context(ph);
hexchat_hook_timer(ph, 1000, timer_cb, context);
hexchat_command(ph, "close"); /* free the context - in practice this would be done by another plugin or by the user, not like this, but for the purposes of this example this simulates the user closing the context. */
return HEXCHAT_EAT_ALL;
}
int hexchat_plugin_init(hexchat_plugin *plugin_handle, char **plugin_name, char **plugin_desc, char **plugin_version, char *arg) {
*plugin_name = "do_ub";
*plugin_desc = "does ub when you /do_ub";
*plugin_version = "1.0.0";
ph = plugin_handle;
/* etc */
hexchat_hook_command(ph, "do_ub", 0, do_ub, "does UB", NULL);
return 1;
}

timer_cb 中的行导致 hexchat 比较(在本例中可能已释放 - 绝对已释放,请参阅 do_ub 中的注释)指针与另一个指针, 如果您关注 here (plugin.c#L1089, hexchat_set_context)你最终会在here (hexchat.c#L191, is_session) .要调用此代码,请在 hexchat 中运行 /do_ub

相关代码:

int
hexchat_set_context (hexchat_plugin *ph, hexchat_context *context)
{
if (is_session (context))
{
ph->context = context;
return 1;
}
return 0;
}

int
is_session (session * sess)
{
return g_slist_find (sess_list, sess) ? 1 : 0;
}

这种东西是UB吗?

最佳答案

C11 Standard draft 6.2.4p2 (Storage durations of objects) 中所述,在指向的对象达到其生命周期结束后使用指针的值是不确定的 (重点是我的):

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

Annex J.2 中所述,使用它的值(仅用于任何用途)是显式未定义的行为 (未定义的行为):

The behavior is undefined in the following circumstances: [...] The value of a pointer to an object whose lifetime has ended is used (6.2.4).

关于c - 比较已释放的指针会调用 UB 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52628773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com