0

What is undefined behaviour in C?

I am using GCC compiler. In some cases I get correct value though the program's output was supposed to be undefined. I ran those programs several times. But the result was consistent. And for some other programs the result was undefined. So, in which cases I should consider that the program behaviour is really undefined? Is there any kind of RULES for this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Tonmoy
  • 557
  • 2
  • 6
  • 20

5 Answers5

2

undefined behaviour means the compiler can emit any code it likes. Your program might show results that you expect or it might format your harddrive or it can start sending emails to the taliban. anything can happen

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
2

The definition of undefined behavior:

C11(ISO/IEC 9899:201x) §3.4.3

1 undefined behavior

behavior, upon use of a non portable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

2 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).

3 EXAMPLE An example of undefined behavior is the behavior on integer overflow.

There is also a list of undefined behaviors in C11 §J.2 Undefined behavior

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

A behavior, upon use of a non-portable or erroneous program construct, of erroneous data, or of indeterminately valued objects, for which this International Standard imposes no requirements.

Example:

i = ++i;

For more you can read this.

Sadique
  • 22,572
  • 7
  • 65
  • 91
0

I think, in simple words, if the behavior of the instruction is not guarenteed to be consistant across all compilers or all situation, you can say it as undefined behavior.

Balamurugan A
  • 1,886
  • 2
  • 17
  • 19
0

This can be illustrated by an example,

#include "stdio.h"


int *ptr;



void func2()
{
  int k = 300;

}

void func1()
{
  int t = 100;

  ptr = &t;
}

int main(int argc, char *argv)
{


  func1();

   printf("The value of t=%d\r\n",*ptr);

  func2();


   printf("The value of t=%d\r\n",*ptr);

}

On my machine, I got the following.

joshis1@(none) temp]$ ./ud.out 
The value of t=100
The value of t=300

This tells that the value of t was not guaranteed. Once the scope of t was over, the stack space was allocated to k. Thus, ptr was accessing the same address - memory location . But the variable scope was over. You will get the consistent result, in case you don't call func2(); Thus, compiler doesn't guarantee the outcome -> This is called the undefined behaviour.

dexterous
  • 6,422
  • 12
  • 51
  • 99