code:
#include<iostream>
using namespace std;
int main()
{
size_t i = sizeof new int;
cout<<i;
}
In GCC compiler, working fine without any warning or error and printed output 8
.
But, in clang compiler, I got the following warning:
warning: expression with side effects has no effect in an unevaluated context [-Wunevaluated-expression]
size_t i = sizeof new int;
sizeof new int;
undefined behavior?sizeof(* int) returns the size of the address value, that is, a byte. address that points to a byte position in memory that stores an int. value. The address values are typically 4 byte integers themselves on a. 32 bit system, so sizeof(*int) would return 4.
It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.
The sizeof operator, returns the size of an expression, or of an object type in C . An expression is for example 1 + 2 , an object is any region of memory, and a type is for example int . The value returned by the sizeof operator, is of type size_t , and its unit is byte.
sizeof() will only work for a fixed size array (which can be static, stack based or in a struct). If you apply it to an array created with malloc (or new in C++) you will always get the size of a pointer.
The warning doesn't state that it's UB; it merely says that the context of use, namely sizeof
, won't trigger the side effects (which in case of new
is allocating memory).
[expr.sizeof] The sizeof operator yields the number of bytes occupied by a non-potentially-overlapping object of the type of its operand. The operand is either an expression, which is an unevaluated operand ([expr.prop]), or a parenthesized type-id.
The standard also helpfully explains what that means:
[expr.context] (...) An unevaluated operand is not evaluated.
It's a fine, although a weird way to write sizeof(int*)
.
new
operator returns pointer to the allocated memory. new int
will return a pointer, therefore sizeof new int;
will return size of a pointer. This is a valid code and there is no undefined behaviour here.
Warning is legit and only warns about the effect of side-effect on the operand and that's because operands of sizeof
is not evaluated.
For example:
int i = 1; std::cout << i << '\n'; // Prints 1 size_t size = sizeof(i++); // i++ will not be evaluated std::cout << i << '\n'; // Prints 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With