C 指向本地外部作用域的指针
函数返回堆栈变量的地址,这将导致非预期的程序行为,通常以崩溃的形式出现。 以下函数返回堆栈地址:C 指向本地外部作用域的指针,c,C,函数返回堆栈变量的地址,这将导致非预期的程序行为,通常以崩溃的形式出现。 以下函数返回堆栈地址: int init(char *device, DriverType driver) { int rv = -1; if (autodetect) { void *md; const char *p = NULL; char buf[PATH_MAX]; *device = 0; md = discov
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;
}
请在代码中帮助解决此问题您大致有两种选择:
char ch[PATH_MAX];
init (ch, ...);
int init(char *device, DriverType driver)
{
/*...*/
device = malloc(PATH_MAX);
/*...*/
}
char* p;
init (p, ...);
free(p);
第一个选项更优雅、更高效。对问题的代码质量没有太大印象:缩进非常奇怪,而且
buf
甚至没有显示声明。更不用说函数是用返回类型int
声明的,但它不返回任何值。通常需要使用break代码>在switch语句中(这里没有关系,因为您使用的是gotos,但是使用break通常是一种好的做法)。正如@KlasLindbäck提到的,函数应该返回一个整数
,但它不返回任何东西。此外,部分try\u v…
将按顺序执行(一个接一个),除非它们包含返回。实际上,我更希望将这些部分定义为单独的函数,并在init中简单地调用它们,因为使用多个goto
s将使您的代码难以调试和遵循(也称为意大利面代码)