Questions tagged [undefined-behavior]

The unpredictable outcome of compiling or executing a program which breaks rules of the language neither compiler, interpreter nor runtime-system have to enforce. DO NOT USE this tag for questions regarding the data type or return value of "undefined". In those cases, the [undefined] tag should be used instead.

Filter by
Sorted by
Tagged with
0 votes
1 answer
113 views

C++: is it undefined behaviour to create with a bitwise copy of an object using a C-style cast to char[] (and back)?

I find this question hard to precisely phrase. I have come across a bizarre situation in a large project of mine where I need to work with lambdas that capture by value. In short, I have something ...
wvn's user avatar
  • 626
-3 votes
0 answers
58 views

Two different definitions of the same class works with -O2 but not with -O0 [duplicate]

I fixed my problem myself, but this gave me a lot of trouble. So, now I'm asking here to understand what actually happened. I defined a simple structure: struct Range { int start; int end; } The ...
JRR's user avatar
  • 3,056
0 votes
1 answer
66 views

When does std::as_writable_bytes trigger undefined behavior

I thought I finally understood reinterpret_cast and strict aliasing, and then I came across this example, slightly modified from the "Invalid scalar" example on https://en.cppreference.com/w/...
Erik Man's user avatar
  • 834
1 vote
3 answers
62 views

My self-made strcpy somehow changed both strings (C)

I made an attempt at a self-made strcpy in and a piece of code that tests what happens when I copy a large string to a small one in C. The first time I successfully ran the code, Y changed, despite ...
PcPlayer's user avatar
2 votes
2 answers
55 views

Dereferencing pointer cast from an integer of a valid memory address give Segmentation fault

I was playing around with c pointer and wrote this code #include <stdio.h> int main() { int a = 17; int* p1 = &a; int* p2 = (int*)(&p1); p1 = (int*)(&p2); printf(...
twowr's user avatar
  • 21
2 votes
2 answers
211 views

Safely check if signed multiplication would overflow in C++17

I'm looking for a convenient idiom to check if a multiplication of two signed integers (longs or long longs) would overflow in versions of C++ where signed arithmetic overflow is undefined behavior (C ...
user3188445's user avatar
  • 4,166
3 votes
1 answer
98 views

What happens if memory for a format string is shared with one of the arguments of printf? [duplicate]

According to the C Standard, the signature of printf() is: int printf(const char * restrict format, ...); As I understand, the meaning of the restrict is that format will be the only reference to the ...
user16217248's user avatar
  • 3,708
0 votes
1 answer
85 views

Why do shared_ptr and unique_ptr have different behavior when dtors are not virtual?

So, I know that not making polymorphic classes destructors virtual will lead to undefined behavior, and the correct fix to this is to make them virtual. With that being said, why does shared_ptr "...
josh chatham's user avatar
2 votes
2 answers
106 views

Is there a failsafe way to determine the alignment/trailing bits of a pointer in C?

In C, a pointer is aligned to a certain if a certain number of trailing bits are zeros. This requires extracting the bits of a pointer, albeit only bounded number of trailing bits. The obvious way is ...
user16217248's user avatar
  • 3,708
1 vote
2 answers
192 views

const_cast vs mutable and undefined behavior

Edit: I edited the code here to not use pointers because there were too many unrelated comments about it #include <iostream> struct Foo { Foo(const int a) : total(a) {} int index ...
asimes's user avatar
  • 5,781
-1 votes
2 answers
98 views

Writing out of boundary matrix

The exercise in an exam required writing on paper the values that the memory obtains after executing the following program. The issue is that in this program, we are accessing unallocated memory when ...
MRn0b0dy's user avatar
0 votes
0 answers
55 views

Is passing the uninitialized variable to function considered UB in C++? [duplicate]

Recently I was writing my raytracer project and made some bugs in it. I have a function: double Length(const Vector& v) { return std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); } and then ...
Greg's user avatar
  • 19
3 votes
1 answer
91 views

Linked list without malloc [duplicate]

I'm starting to learn C myself, and based on the book "Programming in C (4th Edition)", the author defined a linked list as following: struct entry { int value; struct entry *next; };...
Anh Duc Nguyen's user avatar
0 votes
2 answers
122 views

Not returning from a function is not an error?

What's the reasoning that for most major compilers, gcc, clang, nvc produce only a warning while compiling following code (suppressable one). #include <iostream> int foo() { return 42; } ...
Swift - Friday Pie's user avatar
1 vote
1 answer
60 views

Is moving the target of a raw Pointer safe in rust

I'm creating a bidirectional graph in rust and the parent pointer are an obvious problem with the rust borrowing rules so I used raw pointers which are in theory safe since the parent owns the child ...
RedCrafter LP's user avatar
0 votes
0 answers
21 views

Cannot read property 'undefinedProperty'

I was getting this error Error Message: "TypeError: Cannot read property 'undefinedProperty' of null" Tried this and this saved my life! if (myObject && myObject.undefinedProperty) { ...
rupal modi's user avatar
2 votes
1 answer
126 views

Passing a temporary by const pointer instead of const reference; is this workaround well-formed?

Apparently, according to the C++ standard, one can't pass a const pointer to a temporary as an argument to a function, while it's totally fine to pass a const reference instead, even though both ...
dragonroot's user avatar
  • 5,703
0 votes
0 answers
67 views

How to INTENTIONALLY produce a SegFault when testing? [duplicate]

I have a piece of Segment Fault catching codes, it processes SIGSEGV signal from OS, to prevent my app from crashing, at least get a chance to write some logs before exiting. In order to test this ...
Leon's user avatar
  • 1,661
9 votes
1 answer
344 views

"*s = 0" being optimized out. Possible GCC 13 bug? Or some undefined behaviour?

With GCC 13.2, the output of the following code depends on the optimization level: #include <ctype.h> #include <stdio.h> char *SkipAName(char *s) { if (('A' <= *s && *s <= ...
tueda's user avatar
  • 885
0 votes
1 answer
155 views

Does int sum = func(1) + func(2) cause undefined behavior if func() modifies a global variable [duplicate]

Inspired by this SO post, I am wondering whether the below snippet causes UB as both add_func() and mul_func() could modify counter concurrently and in an unspecified order: int counter = 0; int ...
D.J. Elkind's user avatar
1 vote
3 answers
195 views

Placement new + reinterpret_cast in C++14: well-formed?

Consider the following example in C++14: alignas(T) unsigned char data[sizeof(T)]; new (data) T(); T* p = reinterpret_cast<T*>(data); p->something(); // UB? Is this code legal, or are the ...
user1011113's user avatar
  • 1,163
5 votes
3 answers
158 views

Does assigning infinite values to integer types have undefined behavior?

The C Standard specifies how finite floating point values are converted upon storing them into integer types, but it does not seem to specify the behavior for non finite values: 6.3.1.4 Real floating ...
chqrlie's user avatar
  • 136k
2 votes
2 answers
81 views

Safety of using std::ptr::write_volatile for interior mutability in a Copy type (i.e. without UnsafeCell)

I'm trying to achieve interior mutability in a Copy value type (for caching purposes). The problem is that, as far as I can tell, none of the types available for interior mutability (e.g. UnsafeCell ...
Ricardo Machado's user avatar
0 votes
2 answers
74 views

Downcasting base class instance to empty child interface

I was wondering about the validity of downcasting a base child to an empty interface child class. See example below. Basically I want to store data in a generic template free way (reading data from a ...
pnarvor's user avatar
  • 15
-1 votes
1 answer
68 views

Undefined behaviour when a clone of std::function is created

I try to implement a clone of std::function. For simplicity, I want to create a class like std::function which handles types int(*)(int). I am facing an issue with the copy constructor. When the call ...
getsoubl's user avatar
  • 725
0 votes
2 answers
78 views

Reserve memory in base class to be used in derived class c++

I am writing some low level abstractions for communicating with some chip via SPI and I have created registers abstraction to avoid tricky bit manipulation. I thought that i may create interface ...
lukasz luko's user avatar
0 votes
0 answers
60 views

The Output of the C Program '(-x > -y)' Differs on macOS and Linux - Why and How to Fix It [duplicate]

I am attempting to write a simple C program, which produces different output on macOS and Linux. Specifically, my code looks like this: #include <stdio.h> #include <limits.h> int main() { ...
anf4108's user avatar
  • 11
4 votes
1 answer
127 views

Is viewing an integer as an array of smaller integers UB?

Is viewing an integer as an array of smaller integers UB? For example, is there UB in this code: #include <iostream> #include <cstdint> #include <algorithm> // sort void sort_bytes(...
MWB's user avatar
  • 11.9k
1 vote
0 answers
51 views

Exception in destructor - UB or "may result in UB"? [duplicate]

I know it's a very common topic but I haven't been able to find the answer to my specific question. Everyone knows throwing (and not handling) exceptions in destructors is a bad idea and you shouldn't ...
NPS's user avatar
  • 6,083
0 votes
1 answer
105 views

C++ casting int into enum then read that enum as bit field safe or not?

#include <iostream> #include <stdio.h> #include <string> #include <cstring> using namespace std; enum class OrderFlags : uint16_t { None = 0, BuySide = 1, UpdateVolume = ...
Huy Le's user avatar
  • 1,559
0 votes
1 answer
142 views

reinterpret_cast of pointer-to-pointer - is it Undefined Behavior?

We need to cast int** to void**, for which reinterpret_cast can be used. However, is it technically allowed by the C++ Standard, or are we in Undefined Behavior territory? Use case When using Nvidia ...
user1011113's user avatar
  • 1,163
2 votes
1 answer
104 views

Why is dereference of past-the-end iterator of std::basic_string still UB after C++11?

As we all knows, C++11 adds a null terminator to std::basic_string (which doesn't count into most member functions). But when I read cpp ref, I found dereference of end() an UB (this paragraph is ...
998244353's user avatar
3 votes
2 answers
93 views

initial or terminal malloc buffer possible?

Suppose I do something as follows: size_t length = 1000; char* p = malloc(length); and then I want to loop over the elements, so most basic would be: for (size_t i = 0; i < length; ++i) { p[i] = ...
Sasha's user avatar
  • 339
2 votes
3 answers
169 views

Is it undefined behavior to access the object representation of a pointer through a char*?

I know this is weird question, but just bad curious. char* ptr = 0; strcpy( (char*) &ptr, "UB?"); This code means 'I will use the memory of ptr as a char array.' I think 'it's ...
Dean Lee's user avatar
  • 125
2 votes
0 answers
97 views

Check if a `std::string` uses small string optimization (SSO)

I want to check if a std::string value is using the small string optimization (SSO). I am wondering if this is defined behavior: #include <string> #include <cstdint> auto is_sso(const std:...
Chris's user avatar
  • 2,631
0 votes
0 answers
55 views

How to change/examine a value through bit manipulation without being undefined behavior in C++17 or lesser

There are some posts that are related more or less directly to this question but I'm missing a global and accurate answer. For fundamental types, value representation (as defined in the standard) is ...
Oersted's user avatar
  • 1,050
1 vote
4 answers
286 views

Branch prediction and UB (undefined behavior)

I know a little something about branch prediction. This happens at the CPU and has nothing to do with compilation. Although you might be able to tell the compiler if one branch is more likely than the ...
Joel's user avatar
  • 885
2 votes
2 answers
88 views

Is accessing a member of an unaligned union undefined behavior even if the member being accessed is sufficiently aligned?

In C bad things can happen if I try to access a type through a pointer that is not aligned: int x[2]; // Assuming CHAR_BIT == 8 && sizeof(int) == 4 *(int *)((char *)x+1) = 10; /* Undefined ...
user16217248's user avatar
  • 3,708
17 votes
3 answers
2k views

Is it undefined behaviour to use pointer after allocated memory?

I have the following code: uint8_t buffer[16]; uint8_t data[16]; uint8_t buffer_length = 16; uint8_t data_length = 0; memcpy(buffer + buffer_length, data, data_length); memcpy should be a no-op, ...
vbezhenar's user avatar
  • 11.6k
13 votes
1 answer
302 views

Does undefined behaviour retroactively mean that earlier visible side-effects aren't guaranteed?

In C++, a compiler can assume that no UB will happen, affecting behaviour (even visible side-effects like I/O) in paths of execution that will encounter UB but haven't yet, if I understand the ...
Peter Cordes's user avatar
2 votes
1 answer
174 views

cast char * to void **

Suppose I have: char * bufPtr = ...; // points into a char array with at least sizeof(void *) chars remaining void *ptr1 = ...; void *ptr2; Assuming that bufPtr is properly aligned, are the lines *(...
Joshua Green's user avatar
  • 1,555
24 votes
3 answers
4k views

Why is optimization forbidden if a C compiler cannot prove lack of UB?

If a C program has undefined behavior, anything can happen. Therefore compilers may assume that any given program does not contain UB. So, suppose our program contains the following: x += 5; /* Do ...
Joshua's user avatar
  • 351
1 vote
3 answers
66 views

downcasting standard layout struct to derived struct with the same data members

I receive a pointer p to a struct S from C code and want to downcast it in C++ with static_cast<S_extended*>(p) where S_extended is derived from S but just adds some methods to S so that the ...
user396672's user avatar
  • 3,126
15 votes
1 answer
1k views

Is it really well defined to check pointer alignment using the pointer's integer value?

Is there a guaranteed (not implementation-defined!) way to check for pointer alignment? The most common way to query pointer alignment seems to be: convert to integer check whether the integer is a ...
Kietz's user avatar
  • 1,356
7 votes
2 answers
291 views

All programs were UB before C++20?

Yesterday I heard this in a talk from David Stone Prior to C++20 it was not possible to implement std::vector, all vector implementations, if they are written in C++, had undefined behavior. But ...
Enlico's user avatar
  • 23.9k
5 votes
1 answer
132 views

Are these expressions involving compound literals defined in C?

Are these expressions defined? int x = 5, y; y = ++(int){++x}; //or y = (int){x++}++; and (I cant find any reason why not to be defined) int x = 5; x = ++(int){++x}; //or ...
0___________'s user avatar
2 votes
0 answers
48 views

Within a c++ consteval method, is it allowed to refer to the name of a static inline variable to enforce instantiation?

Is this valid c++ 20 or does the code rely on an undefined behavior? #include <iostream> template<int id> struct Registration { consteval auto operator() () const noexcept { ...
eel76's user avatar
  • 117
0 votes
4 answers
132 views

Can I assign or return a struct with unassigned elements in C?

In C, using an uninitialized variable is undefined behavior. Including: int x; int y = x; However, suppose I have the following: struct Struct { int a; int b; }; struct Struct s; s.a = 1; ...
user16217248's user avatar
  • 3,708
5 votes
2 answers
117 views

Is unconditionally creating a pointer to the last element of a vector legal?

I have the following C++ code: void bar(int&); void baz(); void foo(std::vector<int>& v) { int* pointer_to_last = v.data() + (v.size() - 1); if (v.size() > 0 && *...
eyelash's user avatar
  • 3,287
0 votes
2 answers
71 views

C++ "Undefined" vs "Unspecified" behavior for function calls: f(i=-2, i=-2) is no longer undefined vs f(++i, ++i) is unspecified [duplicate]

I know this is one of those "undefined behavior" questions, but a current cppreference page on the subject (as of C++23) itself gives two example's that I'm having trouble understanding from ...
mishar's user avatar
  • 401

1
2 3 4 5
54