2,892 questions
10
votes
3
answers
2k
views
What sequence of operations could possibly have `int i = 1; f(i++, i);` invoke `f(2, 2)`?
This answer says that
i = 1;
f(i++, i)
will not evaluate to f(2, 2) since C++17.
However, I'm struggling to understand why this would have been possible before C++17.
What operations, and in what ...
2
votes
5
answers
302
views
Understanding undefined behaviour
I have read about undefined behaviour for the C3 language here:
https://c3-lang.org/language-rules/undefined-behaviour/
Here is the example from the page.
Assume following code:
uint x = foo();
uint z ...
0
votes
0
answers
104
views
Modifying object representation in presence of padding bits
This question is a follow-up of std::bit_cast padding and undefined behavior. This "revival" is motivated by my answer to Accessing object storage where I proposed a function to modify a ...
2
votes
2
answers
119
views
Is it undefined behaviour to free a `static restrict` array function parameter?
I'm asking this question from the perspective of a compiler developer – I want to know whether a particular potential optimisation is valid (because all programs that the optimisation would break have ...
8
votes
1
answer
866
views
When is reinterpret_cast UB?
Does the code below contain undefined behavior (UB)?
struct A
{
int x;
char y;
};
int main()
{
std::vector<uint8_t> v(sizeof(A), 0);
A* p = reinterpret_cast<A*>(v.data());...
3
votes
2
answers
306
views
Is it ok to write `&*string.end()`?
I see many places in public repositories, where the first and last iterators of std::vector/std::string/std::string_view are converted into pointers using the combination of &* operators. In ...
10
votes
1
answer
528
views
Is this a well-defined way to access bitfield bits by index in C11
The order of bits in C11 bitfields is implementation-defined, and so is any padding in between them. This makes it difficult to access the bitfields by index at runtime, even though most ...
Advice
1
vote
9
replies
206
views
Is this array subscripting behavior really undefined in C?
unsigned int n = 1;
char* s = "X" + 1;
s[-n];
Is that third statement undefined in C23? It seems it is, as by the standard in 6.5.2.1.2:
... The definition of the subscript operator [] is ...
1
vote
4
answers
198
views
Does union "common initial sequence" include bitfields?
As far as I understand, you are allowed to access inactive members of a union, if they share a "common initial sequence" with an active one. This can be used to tag active member with a type ...
6
votes
1
answer
157
views
Is this const_cast in the context of type-erasure undefined behavior?
While looking at this example: https://github.com/PacktPublishing/Hands-On-Design-Patterns-with-CPP-Second-Edition/blob/main/Chapter06/09_function.C
which is an implementation of std::function with ...
2
votes
1
answer
115
views
Hide implementation similar to pimpl without heap allocafion
I am trying to hide some implementation behind an opaque data type. Normally, pimpl would be the preferred pattern, but it requires heap allocation which is not desirable in this context (embedded, ...
5
votes
1
answer
250
views
Is it legal to cast a repr(C) struct pointer to pointer to its first field?
In C, this is legal as far as I know (In C, does a pointer to a structure always point to its first member?).
#include <stdio.h>
typedef struct {
char *name;
int age;
} A;
typedef ...
3
votes
1
answer
184
views
Is aliasing &mut T in Cell<T> undefined behaviour?
Let's say we have a global state OK inside an UnsafeCell, and instead of unsafe { OK.get().as_mut().unwrap() } every time, we create a convenient getter get_mut. Is it UB to call get_mut inside the ...
0
votes
0
answers
116
views
Does std::is_invocable_r with void as return type lead to UB?
Today I stumbled upon weird behavior of std::is_invocable_r.
While doing research for why it is happening, I stumbled upon this question on Stack Overflow:
is_invocable_r ignoring the return parameter
...
1
vote
2
answers
209
views
Is data race between processes UB?
Is data race undefined behaviour only for two threads within same process, or is it UB also between processes?
Definition of Data Race from Rustonomicon:
Safe Rust guarantees an absence of data races,...
15
votes
3
answers
2k
views
Why does a mismatching printf specifier also affect subsequent arguments?
I have a very simple C program where I am printing variables of different sizes.
#include <stdio.h>
unsigned int long long a;
unsigned int c;
int main() {
a = 0x1111111122222222;
c = ...
2
votes
3
answers
189
views
Bitwise operations act outside of type width in C; Compiler Bug or Within Spec?
The following derives from this question but is distinct
Consider the following code sample;
uint32_t *value = malloc(sizeof(uint32_t));
*value = 0xAAAABBBB;
int16_t *subset = (int16_t*) (value);
...
3
votes
5
answers
295
views
Does unsequenced behavior repeat itself?
tl;dr
I have a program that "works", but does so in part via unsequenced behavior. I recognize that code with unsequenced behavior can technically do anything - however, it has to do ...
15
votes
1
answer
1k
views
Is it Undefined Behavior to backport namespace std features to older C++ versions?
According to What are the reasons that extending the std namespace is considered undefined behavior?, adding anything to namespace std is Undefined Behavior, with some exceptions carved out, such as ...
3
votes
2
answers
171
views
Accessing a struct member from what is not the same struct type
The code below looks crazy, because I am interested in finding out the limits of what’s possible, and it isn’t exactly what I’m doing in my real code. It compiles without warnings and works as ...
6
votes
1
answer
245
views
How do I create and use a stack-allocated struct ending with a C99 flexible array member in C++ without undefined behaviour?
I'm calling a 3rd-party C99 library from modern C++. The API contains a struct that ends with a flexible array member. To allocate the struct on the stack I think I need a byte buffer then cast it to ...
5
votes
5
answers
260
views
Is array pointer arithmetic undefined behavior in C for separate translation units?
There are several source code files of a program.
File file_a.c has an array in the global scope, and a function is provided that returns a pointer to its beginning:
static int buffer[10];
int *...
0
votes
1
answer
251
views
Is it safe to use `(void) va_arg(...)` to advance the `va_list` in C? [closed]
I have a C function that uses va_list but needs to skip the first two arguments in here:
static size_t event_type_CURSOR_POS__weight( const void * self, va_list * app )
{
(void) va_arg( *app, ...
4
votes
2
answers
319
views
Obtaining an integer (long) value representing the address of the current object without UB
I'm trying to obtain the address of an object (the current one - *this) for use in seeding a random generator.
I want to do this since I want to take advantage of ASLR for providing a bit of entropy. ...
2
votes
1
answer
207
views
Is difference between two pointers pointing to the same deallocated array well-defined in C++?
int main() {
const int length = 10000;
double *A = new double[length];
double *first = A;
double *last = A + length - 1;
delete[] A;
ptrdiff_t diff = last - first;
}
In C++, ...
22
votes
1
answer
2k
views
Is difference between two pointers pointing to the same deallocated array well-defined in C?
#include <stddef.h>
#include <stdlib.h>
int main(void)
{
const size_t length = 10000;
double* a = malloc(length * sizeof *a);
double* first = a;
double* last = a + length-1;
...
5
votes
1
answer
281
views
How does [[assume]] affect an assert?
The user defined attribute [[assumes(expression)]]
Specifies that the given expression is assumed to always evaluate to true at a given point in order to allow compiler optimizations based on the ...
14
votes
1
answer
384
views
Why does a deducing-'this' lambda require `this` to be a reference or capturing variables by reference?
Why does this code output garbage on GCC, like there is UB?
auto data = std::vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto output = [data](this auto self, size_t i) {
if (i >= 10) {
...
4
votes
2
answers
231
views
Can an integer type with no padding bits have a non-value representation?
I have seen the claim made that, in standard C, reading from an uninitialized object (specifically, an object with indeterminate representation) invokes undefined behavior. This also seems to be how ...
2
votes
1
answer
91
views
Ensure that a mutable reference is dead at a given point in a function, to avoid UB
I'm writing unsafe code. It looks something like this:
fn yield_value(value: &mut T) {
let value_ptr = std::ptr::from_mut(value);
SOME_ATOMIC_PTR.store(value_ptr, Ordering::Release);
// [......
0
votes
0
answers
47
views
Why does SIMD[DType.bool, 4](True, False, True) give unexpected reduce_bit_count() results in Mojo?
I'm investigating the method reduce_bit_count() from Mojo's SIMD API.
According to the documentation:
Returns the total number of bits set in the SIMD vector.
I expected the following behavior:
3 ...
9
votes
1
answer
225
views
Is it UB to twice drop the same value of a type for which needs_drop() returns false?
Basically, the question is in the title. Assume we have a type T, for which std::mem::needs_drop::<T>() == false. Is it UB to drop twice a value of type T?
Here's an example: Consider the ...
2
votes
1
answer
101
views
Initializing Base class and member using the same pointer without UB
While reviewing some testing code, I have come across this situation:
Suppose we have these two classes:
class Project
{
public:
Project(std::string path);
~Project;
// [many more ...
-1
votes
1
answer
81
views
Can I safely assign a non-nil value to a non-optional nil object in Swift?
If you bridge C or Objective-C to Swift, you can misuse _Nonnull to falsely make a guarantee to Swift that a value never holds nil.
However, suppose I have this situation in Swift:
var nonoptional: ...
2
votes
2
answers
179
views
Are unsynchronized writes to global variables UB if code does not read from them? [duplicate]
For the purpose of debugging, our project is sometimes using global volatile variables:
volatile struct {
uintptr_t last_read = 0;
uintptr_t last_write = 0;
size_t reads = 0;
size_t ...
0
votes
1
answer
208
views
Do we really need std::start_lifetime_as if a well-defined alternative already exists?
Consider the code example excerpted from cppref:
#include <complex>
#include <iostream>
#include <memory>
int main() {
alignas(std::complex<float>) unsigned char buf[...
13
votes
1
answer
1k
views
Does C++23 guarantee std::launder can be omitted in placement new scenarios?
#include <iostream>
#include <new>
struct A {
int const n;
void f() {
new (this) A{2};
}
void g() {
std::cout << this->n;
}
void h() {
...
2
votes
1
answer
177
views
Does allocating a buffer smaller than the size of a struct cause undefined behavior, even if I do not reference any would-be out-of-bounds members?
Suppose I have the following:
struct S {
char b[256];
};
struct S *buf = malloc(128);
buf->b[0] = 1;
You may notice that the allocation size is smaller than the structure size, but at no ...
2
votes
2
answers
135
views
In Rust, is it sound to do place projections on raw pointers whose provenance overlaps a mutable reference?
Here's an example of the sort of code I'd like to be able to write for an unsafe Rust program I'm working on:
use core::cell::UnsafeCell;
fn main() {
// create an UnsafeCell holding two `u64`s
...
-3
votes
1
answer
155
views
why does the returning local variable's address in c++ not crash, but still give undefined behavior? [duplicate]
the following is my code:
#include <iostream>
int* foo() {
int a = 5;
return &a;
}
int main() {
int* p = foo();
std::cout << *p; // Output: 5
*p = 8;
std::...
11
votes
2
answers
1k
views
What is "[core] language undefined behavior" as opposed to "undefined behavior"?
Herb Sutter refers to that in Peering Forward - C++’s Next Decade - Herb Sutter - CppCon 2024, and it stresses language several times (e.g. here), so I'd like to understand how to tell it apart from ...
1
vote
1
answer
114
views
Does the IOC (Implicitly Object Creation) apply to my_alloc wrapping std::malloc?
Consider p0593 and the following code:
struct A { std::string s; };
static_assert(std::is_implicit_lifetime_v<A>); // true!
// std::malloc is explicitly BLESSED by the C++23 standard.
// But ...
4
votes
2
answers
255
views
Is it technically UB to static_cast<A*>(memmove(dst, (void*)src, sizeof(src))) since C++20?
Consider the following excerpt from wg21.link/p0593:
A call to memmove behaves as if it
copies the source storage to a temporary area
implicitly creates objects in the destination storage, and then
...
19
votes
1
answer
1k
views
Is it UB to skip the destructor of a derived class before doing a placement new on a base class?
At https://en.cppreference.com/w/cpp/utility/launder.html, there is an example as follows (simplified for brevity, comments mine):
struct Base
{
virtual int transmogrify();
};
struct Derived : ...
13
votes
4
answers
1k
views
Does const char* alias with char*?
I am aware that not all types alias with each other in c. You cannot write to an address with an lvalue of one type, then read from it via an lvalue of another type.
My question is if same system ...
3
votes
3
answers
245
views
Is use of uninitialized static object well-defined in C++?
In the following example,
#include <print>
struct C {
int x;
};
int main() {
static C obj = [] {
obj.x = 3;
return obj;
}();
std::print("{}", obj.x);
}
...
2
votes
2
answers
192
views
Why bind member function works after object destruction?
I've noticed that when you bind a member function, it works even after you destroy the object you bound it to.
Minimal reproducible example:
#include <functional>
#include <iostream>
...
1
vote
1
answer
180
views
Is there a legit way of getting a "copy" of a non-copyable (nor-movable, fwiw) object?
This is not a XY question. I'm curious about what I'm asking. That's it. I'm not going to use std::memcpy() or other things to make copies of non-copyable objects anyway.
I know what copyable means, ...
3
votes
1
answer
105
views
Avoiding undefined behavior when shifting in CUDA
In CUDA I regularly exploit the fact that the hardware does not limit the width of shifts.
This is unlike x86, where only the lower bits of the shift amount are taken into account.
Unfortunately I ...
1
vote
1
answer
159
views
How to implement type punning with memcpy?
I have been working on a toy interpreter, and I want to store all of the variables (which can be ints, doubles or other types) in a big std::vector<char>, but I want to make sure that the way ...