Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does casting a magic address to a pointer in C violate strict aliasing rules?

I know the following code violates strict aliasing rules

int object = 10;
int *pi = &object; // OK
float *pf = (float *)pi; // OK
float f = *pf; // undefined behavior

In the header files of microcontroller peripherals, you can often find code

#define PERIPH_BASE ((uint32_t)0x40000000)
#define I2C1_BASE (APB1PERIPH_BASE + 0x5400)
#define I2C1 ((I2C_TypeDef *) I2C1_BASE)

How legal is it according to the C language standard to access memory through a pointer I2C1?

In its simplest form, the question comes down to how much the code

*(int *)0x1234 = 10;

is it legal and does it have any claims under the strict aliasing rules?

like image 633
Evgeny Ilyin Avatar asked Oct 19 '25 14:10

Evgeny Ilyin


1 Answers

How legal is it according to the C language standard to access memory through a pointer I2C1?

With few exceptions (like the #error directive), the C standard does not say what is legal or not for a program. The C standard says if you write things that conform to the rules it specifies, then the standard defines the behavior.

This does not mean that if you write things that do not conform to the rules, the behavior is not defined. It only means the C standard does not define the behavior. It is still allowed for a compiler to define the behavior.


When you use a compiler that supports embedded programming, it defines the behavior. For such a compiler, there are, in effect, additional objects besides those the C standard defines with its specifications about definitions and allocating memory and whatnot. When you dereference ((I2C_TypeDef *) I2C1_BASE) with such a compiler, you are telling the compiler you are working with an I2C_Typedef object at address I2C1_BASE, and the compiler accepts that.


C 2018 4 7 says:

A conforming program is one that is acceptable to a conforming implementation.

This means that a program that uses features of a conforming compiler that provides extensions to the C language, and is accepted by that compiler, is a conforming program. It does obey the rules of the C standard.

Even if it “violates” the aliasing rules, that violation is rhetorical—it is a method of specifying what the C standard says or does not say in the presence of such a violation. It is not a violation in the sense that your program is not a C program or must be rejected by the compiler. Your program may still be a conforming program.

A program that does not use an extensions and does not have any output dependent on things not fully specified in the standard is a strictly conforming program. You are allowed to write programs that are conforming but not strictly conforming.

like image 184
Eric Postpischil Avatar answered Oct 21 '25 02:10

Eric Postpischil