Question

The C99 standard gives the following definition for undefined behavior:

Behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.

If you're working on a project that will never be required to be portable, that is, the compiler and microcontroller won't change, can you safely use nonportable constructs that the International Standard says will result in undefined behavior if they are defined by the compiler or microcontroller you're using?

Was it helpful?

Solution 2

An implementation is free to define and document some C undefined behaviors.

Rationale document for C99 for example says:

Undefined behavior gives the implementor license not to catch certain program errors that are difficult to diagnose. It also identifies areas of possible conforming language extension: the implementor may augment the language by providing a definition of the officially undefined behavior.

For example, gcc defines some undefined behavior regarding the bitwise shift operator:

GCC does not use the latitude given in C99 only to treat certain aspects of signed '<<' as undefined [...]

http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html

OTHER TIPS

You can always look for additional guarantees from your hardware, OS and compiler vendors. "Undefined behaviour" leaves room for conforming implementations to add guarantees and rules.

Code adds adds 1 to MAX_INT, on a platform which makes no guarantee as to what will happen, there will be no guarantee as to what will happen. If code performs such action on a platform which guarantees that the result will be MIN_INT, then the result is guaranteed to be MIN_INT.

Note that there are many situations (including with integer overflow) where platforms make no guarantees, but will often behave a certain way. Undefined Behavior is still Undefined Behavior on such platforms, since there's no guarantee that any particular action will behave as expected. For example, if SHORT_MAX is 32767, the sequence short foo=32767; foo++; int bar=foo; may very well result in bar being equal to 32768 rather than -32768, even though a compiler which guaranteed two's-complement rollover would have to return the latter result.

Even you are using same IDE on same platform, the undefined behaviour is still unsafe!

For example, this code:

char *p = (char*)0x12345678;
char ch = *p;

This is an undefined behaviour, it depends on the memory allocation. Sometimes, it got a segmentation fault error, and sometimes, it doesn't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top