gpt4 book ai didi

c - 指向本地外部范围的指针

转载 作者:行者123 更新时间:2023-11-30 20:15:23 26 4
gpt4 key购买 nike

函数返回堆栈变量的地址,这将导致意外的程序行为,通常以崩溃的形式出现。以下函数返回堆栈地址:

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;
}

请帮忙解决代码中的这个问题

最佳答案

您大致有两个选择:

  1. 在调用 init 函数之前在堆栈上分配字符:

    char ch[PATH_MAX];
    init (ch, ...);
  2. 使用malloc在函数内部分配char,并在init函数外部释放分配的内存。

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


    char* p;
    init (p, ...);
    free(p);

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

关于c - 指向本地外部范围的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19808553/

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