Search code examples
cundefined-behavioransi-c

Is this also an undefined behavior in Ansi C?


If the code like this, it must be an undefined behavior.

char *String = "Stack Overflow"; //undefined behavior

For this reason, is the following also an undefined behavior? But most of my reference book write like this!

char *Print (char *String)
{
    return String;
}

int main (void)
{
    printf ("%s", Print("Stack Overflow"));
    return 0;
}

To avoid writing an undefined-behavior code, why not doing like this?

char *Print (char String[16])
{
    return String;
}

int main (void)
{
    printf ("%s", Print("Stack Overflow"));
    return 0;
}

Solution

  • If the code like this, it must be an undefined behavior.

    char *String = "Stack Overflow"; //undefined behavior
    

    Must be? Why? No, it isn't. Perhaps it's not the best idea to assign a string literal to a pointer-to-non-const, but as long as you don't modify its contents, it's OK.

    The second construct isn't undefined either. String literals have static storage duration. If you return a pointer to the first character to it, it will be valid regardless of the lifetime and scope of the pointer (as long as it's copied over properly, e. g. it's passed to or returned from a function, which is exactly what happens in your code).