FAQ Database Discussion Community


Can an implementation specify undefined behavior

c,standards,language-lawyer,undefined-behavior,c11
3.4.1 1 implementation-defined behavior unspecified behavior where each implementation documents how the choice is made Can an implementation specify that, implementation-defined behavior is undefined behavior in cases where undefined behavior is a possible outcome? For example: 6.3.1.3 Signed and unsigned integers 3 Otherwise, the new type is signed and...

gcc optimization gives infinite loop or segfault

c,gcc,optimization,segmentation-fault,undefined-behavior
I just found a pretty fun code. GCC optimizations change its behavior weirdly. -O0 works -O1 segfault -O2 infinite loop (from 7 to 1996 inclusive) -O3 works -Og segfault -Ofast works Here's the code : int main(int argc, char *argv[]) { int i, c; c = 0; for (i =...

Is this code really undefined, as Clang seems to indicate?

c++,clang,undefined-behavior,libstdc++,sanitizer
I switched on -fsanitize=undefined on my project which uses Catch, the unit testing library. One line from Catch was signalled as causing undefined behaviour by this flag. I managed to make an isolated example: #include <iomanip> #include <sstream> int main() { std::ostringstream os; os << "0x" << std::setfill('0') << std::hex;...

Safest way to efficiently modify set element that is used as a key

c++,performance,set,undefined-behavior
I have std::set<std::set<T>> whose inner sets I need to modify frequently. How can I do this efficiently? The only ways I can come up with either seem to cause undefined behavior or cause the entire inner set to be copied, both of which seem like bad ideas....

Can we perform deleting object through a pointer to one of its base classes? [duplicate]

c++,language-lawyer,undefined-behavior
This question already has an answer here: Does delete work with pointers to base class? 2 answers Does it cause UB if we define a virtual destructor? For intance: struct A{ virtual ~A(){ } }; struct B : A { }; A *a = new B; int main() {...

Does casting pointers to integers define a total order on pointers?

c++,qt,pointers,undefined-behavior,partial-ordering
(related to my previous question) In QT, the QMap documentation says: The key type of a QMap must provide operator<() specifying a total order. However, in qmap.h, they seem to use something similar to std::less to compare pointers: /* QMap uses qMapLessThanKey() to compare keys. The default implementation uses operator<()....

C++ Cascading destructions of objects with static storage duration

c++,destructor,undefined-behavior,object-destruction
this link says about cascading destructions of objects with static storage duration is popular undefined behaviour in C++. What is it exactly? I can't understand. It will be more good if it is explained with a simple C++ program that can demonstrate this. Your help is greatly appreciated. Thanks

Garbage value in implicit conversion from expression `wchar_t + wchar_t[]` to std::wstring

c++,implicit-conversion,undefined-behavior
I have come across something weird in Visual Studio C++ 2013 Community Edition which is either a compiler bug or I'm writing invalid code that does compile without warnings. Consider the following snippet: #include <string> #include <iostream> int main() { std::wstring text; wchar_t firstChar = 'A'; text = firstChar +...

Can assignment from a const_iterator dereference cause undefined behaviour?

c++,pointers,pass-by-reference,undefined-behavior,const-iterator
This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers. #include <iostream> #include <list> using namespace std; typedef int* intp; typedef std::list<intp> intplist;...

Is it safe to return a passed-in temporary value and read from it in the same statement?

c++,variable-scope,undefined-behavior
I just wrote this without thinking too hard about it. It seems to work fine, but I'm not sure if it's strictly safe. class Foo { struct Buffer { char data [sizeof ("output will look like this XXXX YYYY ZZZZ")]; }; const char * print (const char * format =...

Strange C++ behavior. Value gets overriden

c++,scanf,undefined-behavior
#include <iostream> #include <stdio.h> using namespace std; int main(){ int t; scanf("%d",&t); while(t--){ long long int val; char op; scanf("%lld",&val); while(true){ long long int x; scanf("%s",&op); if(op=='=')break; scanf("%lld",&x); cout<<"***"<<t<<endl; if(op=='+')val+=x; else if(op=='-')val-=x; else if(op=='*')val*=x; else val/=x; } printf("%lld",val); } } In the above code, I can't understand why the value...

Does not evaluating the expression to which sizeof is applied make it legal to dereference a null or invalid pointer inside sizeof in C++?

c++,language-lawyer,sizeof,undefined-behavior,null-pointer
First of all, I've seen this question about C99 and the accepted answer references operand is not evaluated wording in the C99 Standard draft. I'm not sure this answer applies to C++03. There's also this question about C++ that has an accepted answer citing similar wording and also In some...

Is a misaligned load due to a cast undefined behavior?

c,casting,undefined-behavior,memory-alignment
Is a misaligned load due a a cast from void* undefined behavior? Here's what I am seeing with Clang and its sanitizers: bufhelp.h:146:29: runtime error: load of misaligned address 0x7fff04fdd0e1 for type 'const uintptr_t' (aka 'const unsigned long'), which requires 8 byte alignment 0x7fff04fdd0e1: note: pointer points here 00 00...

Ambiguity in the standard on undefined behaviour of out of range pointer

c++,c++11,language-lawyer,semantics,undefined-behavior
ISO IEC 14882-2011 §5.7/5 States: If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. This section is used here on stackoverflow...

C++: call pure virtual function from member function of same class

c++,undefined-behavior,pure-virtual
I know there are already these type of questions asked on SO, but my question is different. so please read my question entirely before marking it as duplicate. Consider following 2 programs. #include <iostream> using std::cout; class Base { public: virtual void f()=0; void g() { f(); } virtual ~Base()...

Is this considered undefined behaviour in C/C++? [duplicate]

c++,c,undefined-behavior
This question already has an answer here: 3 plus symbols between two variables (like a+++b) in C [duplicate] 3 answers int x = 2; int y = 5; int z = x +++ y; printf("%d",z); Both VC++ and GCC give 7 as output. My confusion here is, it could...

Why printf is not printing garbage value?

c,gcc,default,undefined-behavior,garbage
#include<stdio.h> void foo(){ int i; printf("%d\n",i); //should print garbage value } void main(){ foo(); } foo should print garbage value of i. But instead it is printing zero. Why is that? I am using gcc version 4.9.2....

Does the following chained assignment cause Undefined behavior?

c,variable-assignment,language-lawyer,undefined-behavior
Does the following code invoke undefined behavior in C? int a = 1, b = 2; a = b = (a + 1); I know that the following does invoke UB: a = b = a++; The reason is that it violates the following clause from the standard: Between the...

Is modifying the pointed value and the pointer at the same time UB

c++,c,language-lawyer,undefined-behavior
I know that C and C++ and different languages, but the following applies to both. TL/DR I know that i = i++; is UB, because i is modified twice in the expression and C and C++ forbids it. References : C99 6.5 : If a side effect on a scalar...

C operator += Sequence point?

c,pointers,language-lawyer,undefined-behavior,sequence-points
Is this defined behaviour? *p += *p--; And, if it is, is it equivalent to { p[0] += p[0]; --p; } or to { p[-1] = p[0]; --p; } ? I'm guessing the being defined or not depends on whether += has an implicit sequence point and, if it has,...

How will be operands inside (a += 3, 5, a) are going to dealt or caculated in order to print the value of “a”?

c,undefined-behavior
The code snippet is: int main() { int a = 1, b = 2, c = 3; printf("%d", a += (a += 3, 5, a)); } Though it displays 8 in the terminal as an output. But am not getting the concept behind it....

C++ pointer weird undefined behaviour

c++,pointers,undefined-behavior
Compiling with -O2 (or -O3 for that matter) and running this program yields interesting results on my machine. #include <iostream> using namespace std; int main() { // Pointer to an int in the heap with a value of 5 int *p = new int(5); // Deallocate the memory, but keep...

destruction of static storage duration objects & undefined behavior

c++,destructor,undefined-behavior
C++ standard section 3.6.1 says that Calling the function std::exit(int) declared in <cstdlib> terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration If std::exit is called to end a program during the destruction of an object with static storage duration, the...

Adding two integer variables and displaying output C

c,printf,undefined-behavior,format-specifiers
I am trying to create a simple program in C, that adds two numeric variables. I have tried to validate the inputs, however now the program does not display an answer, simply 0.000000000 #include<stdio.h> int input, temp, status, numberOne, numberTwo, ans; int main(void){ first(); second(); add(); } int first(void){ printf("Please...

Is the sequencing of this decrement invoking undefined behaviour?

c++,undefined-behavior
I am looking for confirmation, clarification is this code well defined or not. It is very common to erase elements of a container in a loop by re-assigning the iterator to the result of the container's erase() function. The loop is usually a little messy like this: struct peer {...

Why passing string to scanf() compiles fine in C?

c,scanf,undefined-behavior
I recently wrote a simple program where I by mistake use scanf() instead of printf() for displaying a message on console. I was expecting to get compile time error, but it compiles fine without warnings & crashes at runtime. I know that scanf() is used for taking input from keyboard....

Is an attempt to modify a const_cast-ed, but dynamically allocated constant object still undefined behavior? [duplicate]

c++,compiler-optimization,heap-memory,undefined-behavior,const-cast
This question already has an answer here: Can a heap-allocated object be const in C++? 6 answers For example: const int* pc = new const int(3); // note the const int* p = const_cast<int*>(pc); *p = 4; // undefined behavior? In particular, can the compiler ever optimize away the...

Is this undefined behavior or a false positive warning?

c++,constructor,undefined-behavior,clang++
Consider the following code: class A { private: int a; public: A(int a) : a(a) { } }; class B : public A { private: int b; bool init() { b = 0; return true; } public: // init() is a hack to initialize b before A() // B() :...

Is it legal to call memcpy with zero length on a pointer just past the end of an array?

c,pointers,language-lawyer,undefined-behavior
As answered elsewhere, calling functions like memcpy with invalid or NULL pointers is undefined behaviour, even if the length argument is zero. In the context of such a function, especially memcpy and memmove, is a pointer just past the end of the array a valid pointer? I'm asking this question...

Why does glGetProgramiv GL_ACTIVE_UNIFORMS occasionally return garbage and crash my program?

c++,c,opengl,driver,undefined-behavior
I have adapted some code from Anton's opengl tutorial companion code found here: https://github.com/capnramses/antons_opengl_tutorials_book/blob/master/02_shaders/main.c In testing the print_all or dump_all function to print everything about a shader, I have noticed in my log that glGetProgramiv(shader_program, GL_ACTIVE_UNIFORMS, &params) will put a garbage value that is either extremely negative(and doesn't do anything...

Can I sort an array of pointers in order to remove duplicates?

c,pointers,undefined-behavior
Let's say I defined a structure and created a few instances of it. I have an array of pointers to these instances but some pointers point to the same instances of my structure. I want to remove duplicates in the array so I sort it by qsort() function. Here's my...

Seg fault on GCC4.6 when trying to move a large bitset, is this a compiler bug?

c++,gcc,segmentation-fault,undefined-behavior,move-semantics
I've experienced a problem with a crash due to return an rvalue of a bitset when the bitset is large. Is this a compiler bug or have I mistakenly done something that caused undefined behaviour? The code below crashes on GCC 4.6.3 with the -std=c++0x flag set. #include <bitset> //...

Is i=i+1 an undefined behaviour?

c,increment,undefined-behavior
I'm using codeblocks and it is giving a different output to other compilers and I can't find a solution to it.What's the undefined behaviour in this program and is there any solution to avoid it? This is the code to print the nth number in a number system with only...

reinterpret_cast from object to first member

c++,c++11,type-conversion,undefined-behavior,reinterpret-cast
I was looking at this answer and I was wondering if casting an object to its first member with reinterpret_cast and using the result could be safe in C++. Let's assume that we have a class A, a class B and an instance b of B: class A{ public: int...

Why compiler is not issuing error while passing an int (not int *) as the argument of scanf()?

c,scanf,undefined-behavior
I tried the below c program & I expected to get compile time error, but why compiler isn't giving any error? #include <stdio.h> #include <conio.h> int main() { int a,b; printf("Enter a : "); scanf("%d",&a); printf("Enter b : "); scanf("%d",b); printf("a is %d and b is %d\n",a,b); getch(); return 0;...

Undefined behaviour or may be something with memset

c++,undefined-behavior
I was trying to save the binary equivalent of a 32 bit number in an array A. For testing my showbits() function , I choosed 8,9 when I came across this thing: I am facing an unreasonable thing in my code when I am placing memset in the function showbits(),I...

printf() with no arguments in C compiles fine. how?

c,printf,undefined-behavior
I tried the below c program & I expected to get compile time error, but why compiler isn't giving any error? #include <stdio.h> int main(void) { printf("%d\n"); return 0; } Why output is compiler dependent? Here is the output on various compilers Output on Orwell Dev C++ : 0 Output...

Does freeing a pointer which was assigned to another pointer of another type (allocated by `malloc`) invoke Undefined Behavior?

c,pointers,memory,free,undefined-behavior
The title maybe confusing. Suppose str is a pointer allocated by malloc. ptr, of type int*, is assigned to it and is freed as shown by the code snippet below: char* str = malloc(64); int* ptr = str; free(ptr); I've tried to compile the above code. It just gives a...

Why is initialization of a new variable by itself valid?

c++,initialization,undefined-behavior,variable-declaration
Consider some code: #include <iostream> int main() { using std::cout; int a=3; cout << "a="<<a<<"\n"; { int a=a; cout << "new a = " << a << "\n"; a=5; cout << "a = " << a << "\n"; } cout << "old a = " << a << "\n"; }...

C++ class merging, linker issue

c++,linker,undefined-behavior
Let's consider the following situation I've discovered today by browsing through a pretty large codebase (real source exemplified for the sake of example): One of the teams created the following two files and a set of interfaces (MoreBase, Base). All is fine till this point. * file1.h * class MoreBase...

Can an uninitialized automatic volatile variable in C be safely read?

c,volatile,undefined-behavior
In C, can I access an automatic volatile variable without having to initialize it first, or does it always result in undefined behavior? E.g., in some hardware devices mapped to volatile variables, initializing the variable makes no sense anyway, or might even be forbidden....

Destroy-and-regenerate assignment operator: what if I'm careful?

c++,destructor,undefined-behavior
This is a bad pattern. Copy-and-swap is better. foo & operator = ( foo const & other ) { static_assert ( noexcept( new (this) foo() ), "Exception safety violation" ); this-> ~ foo(); try { new (this) foo( other ); } catch (...) { new (this) foo(); // does not...

Example of error caused by UB of incrementing a NULL pointer

c++,undefined-behavior
This code : int *p = nullptr; p++; cause undefined behaviour as it was discussed in Is incrementing a null pointer well-defined? But when explaining fellows why they should avoid UB, besides saying it is bad because UB means that anything could happen, I like to have some example demonstating...