C99转到过去的初始化 [英] c99 goto past initialization

查看:194
本文介绍了C99转到过去的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调试崩溃,我碰到这个问题在一些code来了:

While debugging a crash, I came across this issue in some code:

int func()
{
    char *p1 = malloc(...);
    if (p1 == NULL)
        goto err_exit;

    char *p2 = malloc(...);
    if (p2 == NULL)
        goto err_exit;

    ...

err_exit:
    free(p2);
    free(p1);

    return -1;
}

在第一的malloc失败时,会出现问题。因为我们整个 P2 的初始化跳,它包含随机数据,并调用免费(P2)可能会崩溃。

The problem occurs when the first malloc fails. Because we jump across the initialization of p2, it contains random data and the call to free(p2) can crash.

我希望/希望这会被对待的方式相同,C ++编译器在哪里不允许转到跨初始化跳。

I would expect/hope that this would be treated the same way as in C++ where the compiler does not allow a goto to jump across an initialization.

我的问题:跨由标准允许初始化跳跃或这是GCC的实现C99的一个bug

My question: is jumping across an initialization allowed by the standard or is this a bug in gcc's implementation of c99?

推荐答案

您可以要求GCC当你跳过一个变量定义通过向您发出警告 -Wjump门柱-INIT 然后你可以使用 -Werror 来强制用户来处理它。包括在此警告-Wc ++ - compat的所以GCC的开发者都知道,code用C具有不同的行为与C ++

You can ask gcc to warn you when you jump over a variable definition by using -Wjump-misses-init and then you can use -Werror to force the users to deal with it. This warning is included in -Wc++-compat so the gcc developers are aware that the code behaves differently in C versus C++.

您也可以改变code稍微:

You could also change the code slightly:

int func()
{
    char *p1 = malloc(...);
    if (p1 == NULL)
        goto err_exit_1;

    char *p2 = malloc(...);
    if (p2 == NULL)
        goto err_exit_2;

    ...

err_exit_2:
    free(p2);
err_exit_1:
    free(p1);

    return -1;
}

...并只保留配对标签与初始化变量。你有同样的问题与调用带有未初始化变量诸多功能,免费恰好是一个比较明显的。

... and just keep pairing labels with initialized variables. You'll have the same problem with calling many other functions with unitialized variables, free just happens to be a more obvious one.

这篇关于C99转到过去的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆