Pieter van den Ham
Pieter van den Ham

Reputation: 4484

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.

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

Upvotes: 0

Views: 235

Answers (1)

Bathsheba
Bathsheba

Reputation: 234725

Yes.

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.

Upvotes: 3

Related Questions