-4

I have found an "unexpected" behavior of the following code, which modifies a static const int by derefering its pointer:

#include <stdio.h>

static const int a;

int main(int argc, char *argv[])
{
    printf("a=%d\n", a);
    *((int *) &a) = 120;
    printf("a=%d\n", *((volatile *) &a));
    printf("a=%d\n", a);
    return 0;
}

The output of the program compiled with GCC Debian 4.9.2-10 (as well as Debian 4.4.5-8 with -Os) is:

a=0
a=120
a=0

It seems that the compiler optimises the variable value, unless a volatile cast is used. No warning is given during the compilation, and I find strange that the program behaves different in Debian 4.4.5-8 with -Os. Indeed, if no size optimisation is requested, it prints the "expected" value of 120 on the third line.

Is this the normal behavior?

Thanks a lot in advance for your comments

  • Any reason you expect a `const` qualified variable to be modifyable? Your compiler should warn, why do you ignore it? Also "deferring" is something very different! You mean **dereference**. – too honest for this site Jun 06 '16 at 11:30
  • Thanks @Olaf for the comment; I corrected the typo. The compiler issues no warning, even when I use -Wall or -Wpedantic. – Alejandro Homs Jun 06 '16 at 12:30

1 Answers1

1

Is this the normal behavior?

No, it is Undefined Behavior because you modified an object defined with const qualifier:

*((int *) &a) = 120;

This means that whatever can happen and you should not make any assumptions what is correct or not.

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
  • Thanks @grzegorz-szpetkowski for clarifying that a *const* object should not be modified. It is consistent with the fact that the same compiler creates a page-fault exception if one tries to modify an initialised *static const int* (located in a *rodata* section), suggesting that such operations should be avoided. – Alejandro Homs Jun 06 '16 at 14:24