[英]Is declaring an array inside an if statement and using it outside undefined behavior?
Consider this snippet: 请考虑以下代码段:
void init_seed(char *key)
{
char *seed = key;
size_t seed_len = strlen(seed);
// Make sure the seed is at least 12 bytes long
if (seed_len < 12) {
char new_seed[13];
for (int i = 0; i < 12; i++)
new_seed[i] = seed[i % seed_len];
new_seed[12] = '\0';
seed = new_seed;
}
/* Use the seed variable */
}
The reason I declared it this way is that I do not want to use malloc()
in this function, because it will complicate the function quite a lot. 我声明这样说的原因是,我不希望使用
malloc()
在这个函数,因为它将复杂的功能相当多。
The function works as intended (gcc 4.8.4). 该功能按预期工作(gcc 4.8.4)。 However, does declaring
new_seed
inside the if statement and then assigning it to seed
cause undefined behavior? 但是,在if语句中声明
new_seed
然后将其分配给seed
会导致未定义的行为?
Yes . 是的 。
Once new_seed
is out of scope, you no longer own any memory that was allocated for it. 一旦
new_seed
超出范围,您将不再拥有为其分配的任何内存。
So the behaviour on dereferencing the newly assigned value of seed
is undefined . 因此,取消引用新分配的
seed
值的行为是不确定的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.