Many times we talk about undefined behavior, not specified and defined by the implementation in c
. However, what is the difference between these concepts?
Many times we talk about undefined behavior, not specified and defined by the implementation in c
. However, what is the difference between these concepts?
Appears when the behavior of an algorithm has errors that, while generating valid code, the final result will be dependent on such pilgrim factors as the platform on which it is executed or the compiler chosen to generate the program.
char* cadena = "Hola a todos";
cadena[0] = 'h';
The previous example causes an 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 the memory that supports writes, the code will work without problems.
Other examples of undefined behavior:
int* ptr;
free(ptr);
int* ptr = (int*)malloc(sizeof(int));
free(ptr);
free(ptr);
int a = 10;
int b = a/0;
int func(int a, b)
{
int c = a + b;
}
In this case there will be compilers that can show you a warning but it is not convenient to get used to depend on them since it is not something that will be guaranteed (whichever they appear).
Unspecified behavior is found in those situations where the standard gives the compiler some freedom when choosing the order in which instructions are executed.
void func(int a, int b)
{
printf("%d %d",a,b);
}
int i=0;
func(i++,i++);
The previous example can print several results:
0 0
0 1
1 0
And everything depends on the order in which the increments are evaluated ... what depends on 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é , web developer cplusplus .com ) gave a talk on precisely the subject you are asking: Unspecified vs Undefined Behavior 1 .
In summary, he indicated that the unspecified behavior is a correct code whose effect is not specified in standard, its behavior depends on how the compiler implements it and sometimes, the standard limits or outlines it. Keep in mind that you can be consistent, or not be.
On the other hand, the undefined behavior is a 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 behavior defined by the implementation , which is a correct code whose effect is not specified in standard, its behavior depends on how the compiler implements it and sometimes, the standard limits or outlines it and unlike unspecified behavior, it must be documented in the standard and be consistent.