Search code examples
cconstantsundefined-behavior

Is conditionally not modifying constant data undefined behavior in C?


We have the following function:

void foo(int flag, void *ptr) {
    if (flag)
        strcpy(ptr, "Hello World");
    code_that_does_not_attempt_to_modify_data_pointed_to_by(ptr);
}

Would the following be valid:

const char *string_literal_ptr = "String literals are constant and may not be modified";
foo(0, string_literal_ptr);

We are passing a pointer to constant data to a function that may (but will not because we passed 0 as flag) modify the data pointed to by the pointer. Is this valid, given that at no point the program control reaches the point of modifying the constant data? Or is the mere existence of a non const pointer that points to const data invalid somehow?


Solution

  • If flag is false then strcpy(ptr, "Hello World"); is not evaluated, and the fact that ptr points to the data of a string literal is irrelevant.

    If code on unexecuted paths could cause undefined behavior (due to its evaluation, not due to some grammar constraint that arises during translation), then C would break throughly, as tests for null pointers would not work:

    if (p)
        Use pointer p to do something.