比较一个已经空闲的指针调用UB吗?

Son*_*Ex2 8 c undefined-behavior hexchat

这似乎是一个相当常见的模式,例如在hexchat中(可能无法编译,另请参阅插件文档.还请注意,这些文档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;
}
Run Code Online (Sandbox Code Playgroud)

该行timer_cb导致hexchat比较(可能是免费的 - 在这个例子中肯定是免费的,看到注释do_ub)指针与另一个指针,如果你从这里开始(plugin.c#L1089,hexchat_set_context)你将结束在这里(hexchat.c#L191,is_session).要调用此代码,请/do_ub在hexchat中运行.

相关代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

这是UB的事吗?

Eug*_*Sh. 7

在指向的对象到达它的生命周期结束后使用指针的值是不确定的,C11标准草案6.2.4p2(对象的存储持续时间)中所述(重点是我的):

对象的生命周期是程序执行的一部分,在此期间保证为其保留存储.存在一个对象,具有一个常量地址,并在其整个生命周期内保留其最后存储的值.如果在其生命周期之外引用对象,则行为未定义.当指针指向(或刚刚过去)的对象到达其生命周期的末尾时,指针的值变得不确定.

使用它的值(仅适用于任何事物)是一个明确的未定义行为,附件J.2(未定义行为)中所述:

在以下情况下,行为未定义:[...]使用指向生命周期结束的对象的指针的值(6.2.4).