Many times we talk about undefined, unspecified and implementation-defined behavior in c
. However, what is the difference between these concepts?
Many times we talk about undefined, unspecified and implementation-defined behavior in c
. However, what is the difference between these concepts?
undefined behavior
It appears when the behavior of an algorithm has errors that, although they generate valid code, the final result will depend on factors as strange as the platform on which it is executed or the compiler chosen to generate the program.
The above example causes undefined behavior because the string is likely to be stored in a read-only region. In that case the attempt to modify it will cause a runtime error. On the other hand, if the string is stored in a region of memory that allows writing, the code will work without problems.
Other examples of undefined behavior:
free on unreserved memory
call free twice in a row (particularity of the previous case)
Division by 0
return omission
In this case there will be compilers that can show you a warning but it is not convenient to get used to depending on them since it is not something that is going to be guaranteed (that they appear).
unspecified behavior
Unspecified behavior is found in situations where the standard gives the compiler some freedom in choosing the order in which statements are executed.
The above example can print multiple results:
And it all depends on the order in which the increments are evaluated... which is up to the compiler.
In October 2014, at the Carlos III University (Madrid) an event of technical talks on C++ took place, one of the speakers ( Juan Soulié , developer of the cplusplus.com website ) gave a talk precisely on the subject you are asking about: Unspecified vs Undefined Behavior 1 .
In short, he stated that unspecified behavior is correct code whose effect is not specified in the standard, its behavior depends on how the compiler implements it, and is sometimes limited or outlined by the standard. Keep in mind that it may or may not be consistent.
On the other hand, undefined behavior is syntactically correct code whose effect is not specified in the standard and its effect can be any 2 .
Additionally, the talk introduces the concept of implementation-defined behavior , which is a correct code whose effect is not specified in the standard, its behavior depends on how the compiler implements it and sometimes, the standard limits or outlines it and unlike the behavior not specified, must be documented in the standard and be consistent.