- #1
- 4,770
- 3,817
I really would appreciate seeing what opinions* there are on undefined behavior in C. Based
on only the code snippets (A, B, C, D, E (yes, they have issues)) below and:
From N1570 (C 11 standard draft)
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
This is what the standard says about Undefined Behavior, definitions:
Can you defend your position? There are discussions like this elsewhere on the internet.
* I used the word opinions above on purpose. I will explain later.
on only the code snippets (A, B, C, D, E (yes, they have issues)) below and:
From N1570 (C 11 standard draft)
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
This is what the standard says about Undefined Behavior, definitions:
Section 3.4:
behavior
external appearance or action
Section 3.4.3:
undefined behavior
behavior, upon use of a nonportable or erroneous program
construct or of erroneous data, for which this International Standard imposes no
requirements
NOTE: Possible undefined behavior ranges from ignoring the situation completely
with unpredictable results, to behaving during translation or program execution
in a documented manner characteristic of the environment (with or without the
issuance of a diagnostic message), to terminating a translation or execution
(with the issuance of a diagnostic message).
Code:
// Specifically, do these snippets result in UB:
// A
unsigned diff(unsigned a, unsigned b)
{
return a - b;
}
// B
int *foo(void)
{
int *p=malloc(4);
if(p)
*p=13;
return p;
}
// C
int foo(void)
{
foo_2();
int x;
return x/2;
}
// D
int main(void)
{
int i=0;
return ( i + 1 ) + ( i + 2);
}
//E
int main(void)
{
int i=13;
5/0;
return i;
}
* I used the word opinions above on purpose. I will explain later.
Last edited: