Search code examples
cpointersconstantsundefined-behavior

Is it undefined behavior to modify a value that I also have a const pointer pointing to


Does the following scenario have undefined behavior?

void do_stuff(const int *const_pointer, int *pointer) {
    printf("%i\n", *const_pointer);
    *pointer = 1;
}

int data = 0;
do_stuff(&data, &data);

If this is undefined behavior it could probably cause problems if the compiler assumes that the value that const_pointer points to never changes. In this case it might reorder both instructions in do_stuff and thereby change the behavior from the intended printf("0") to printf("1").


Solution

  • If the compiler can prove that the value pointed to by a pointer to const will not change then it will not need to reload the value, or keep the ordering.

    In this case this cannot be done because the two pointers may alias, so the compiler cannot assume the pointers don't point to the same object. (The call to the function might be done from a different translation unit, the compiler doesn't know what is passed to the function.)

    There is no undefined behavior in your example, and you are guaranteed that the printf() will output 0.