指向本地范围之外 [英] Pointer to local outside scope

查看:136
本文介绍了指向本地范围之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个函数返回堆栈变量,这将导致意外的程序行为,通常是在碰撞形式的地址。
下面的函数返回一个堆栈地址:

A function returns the address of a stack variable, which will cause unintended program behavior, typically in the form of a crash. The following function returns a stack address:

int init(char *device, DriverType driver)
{
    int rv = -1;

    if (autodetect) {
        void *md;
        const char *p = NULL;
        char buf[PATH_MAX];

        *device = 0;
        md = discover_media_devices();
        if (!md) {
            fprintf (stderr, "open: Failed to open \"auto\" device");
            if (*device)
                fprintf (stderr, " at %s\n", device);
            else
                fprintf (stderr, "\n");
            goto failure;
        }

        while (1) {
            p = get_associated_device(md, p, MEDIA_V4L_RADIO, NULL, NONE);
            if (!p)
                break;
            snprintf(buf, sizeof(buf), "/dev/%s", p);
            device = &buf[0];
        }

    free_media_devices(md);
    /* out_of_scope: Variable "buf" goes out of scope */
    }

    switch (driver) {
            case DRIVER_ANY:
            case DRIVER_V4L2:
            default:
                    goto try_v4l2;
            case DRIVER_V4L1:
                    goto try_v4l1;
    }

try_v4l1:
    dev = v4l1_radio_dev_new();
    /* use_invalid: Using "device", which points to an out-of-scope variable "buf" */
    rv = dev->init (dev, device);
    ----------------------------

try_v4l2:
    dev = v4l2_radio_dev_new();
    /* use_invalid: Using "device", which points to an out-of-scope variable "buf" */
    rv = dev->init (dev, device);
    ----------------------------

failure:
    return rv;
}

请帮助code来解决这个问题。

Please help to solve this issue in code

推荐答案

您大致有两种选择:


  1. 分配堆栈上的字符调用之前比的的init 的功能:

char ch[PATH_MAX];
init (ch, ...);


  • 使用分配函数内部的字符的的malloc 的和免费分配的内存以外的的init 的功能。

  • Allocate the char inside the function using malloc, and free the allocated memory outside the init function.

    int init(char *device, DriverType driver)
    {
         /*...*/
         device = malloc(PATH_MAX);
         /*...*/
    }
    
    
    char* p;
    init (p, ...);
    free(p);
    


  • 第一个选项是更优雅和高效。

    The first option is more elegant and efficient.

    这篇关于指向本地范围之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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