Example of invalid code

I was reading this book http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html and I settled on one of the examples. In my opinion, this is not true. I think there is no undefined behavior. Am I wrong? Here he is:

Taking the address of a data object of a type that is not a constant and placing it in a pointer to a const-based version is type safe and explicitly allowed; you will be able to use a pointer to inspect the object, but not modify it. Putting an address of type const into a pointer to an unqualified type is more dangerous and therefore prohibited (although you can get around this using casting). Here's an example:

#include <stdio.h>
#include <stdlib.h>

main(){
        int i;
        const int ci = 123;

        /* declare a pointer to a const.. */
        const int *cpi;

        /* ordinary pointer to a non-const */
        int *ncpi;

        cpi = &ci;
        ncpi = &i;

        /*
         * this is allowed
         */
        cpi = ncpi;

        /*
         * this needs a cast
         * because it is usually a big mistake,
         * see what it permits below.
         */
        ncpi = (int *)cpi;

        /*
         * now to get undefined behaviour...
         * modify a const through a pointer
         */
        *ncpi = 0;

        exit(EXIT_SUCCESS);
}

      

Example 8.3 As the example shows, one can take the address of a persistent object,> generate a pointer to a volatility, then use a new pointer. This is a bug in your program and the results are undefined.

This example ncpi

finally points to i

rather than ci

. So I think it makes this example wrong - there is no undefined behavior when changing non const

with a pointer. Do you agree?

+3


source to share


2 answers


I agree: this is the wrong example. The code itself demonstrates certain behavior.

The comment before the final assignment *ncpi = 0;

is inconsistent with the code. The author probably intended to do something different.




My first answer was as if the code was rewriting const

: I revised my answer.

+4


source


It's undefined because it can be stored in read-only memory, for example. This is not the case for x86 systems, but we have a whole host of other issues here, such as alias issues if you enable big optimizations.



Anyway, even just intuitively, why do you think that changing const

by pointer to it that the compiler cannot statically check would be safe?

-2


source







All Articles