Pete Pete - 1 year ago 59
C Question

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];
strcpy(new_seed, seed);
memcpy(new_seed + seed_len, seed, 12 - seed_len);

seed = new_seed;

/* Use the seed variable */

The reason I declared it this way is that I do not want to use
in this function, because it will complicate the function quite a lot.

The function works as intended (gcc 4.8.4). However, does declaring
inside the if statement and then assigning it to
cause undefined behavior?

Answer Source


Once new_seed is out of scope, you no longer own any memory that was allocated for it.

So the behaviour on dereferencing the newly assigned value of seed is undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download