Re[7]: integer overflow
От: Masterkent  
Дата: 10.11.11 11:10
Оценка: +1
Goodhope:

G>3 + 0xff = 2 для беззнаковых 8-ми битных интов. Не?


При сложении двух беззнаковых 8-битных целых каждый операнд перед вычислением суммы будет преобразован к int (в представлении которого по стандарту должно быть не менее 16 бит), и результат вычисления суммы также будет иметь тип int. Естественно, при таком раскладе ни о каком переполнении не может быть и речи (пока результат явным образом не пытаются запихнуть в 8-битное целое, но это уже другой разговор).
Re[8]: integer overflow
От: jyuyjiyuijyu  
Дата: 10.11.11 12:08
Оценка:
я в итоге запилил как в STL правда все пропало с тех пор как умерла ось
и была переустановлена
например у меня была функция max_size() которая имела такой вид
size_t max_size()
{
    return ((size_t)-1) / element_size_
}

выдавала максимально возможное число элементов в контейнере
потом так например
... add(void* data, count)
{
    if (max_size() - size_ < count)
        assert(blah blah)
    if (alloc_size_ < size_ + count)
        realloc(...
    
    memmove(... , , count * element_size_)
}

size_ хранил текущее количество в итоге можно было безопасно умножать
после такой проверки ну и
 
size_t c = a + b;
assert(c >= std::min(a, b));

реально помогал в некоторых местах в итоге тогда получился реально
безопасный контейнер левые циферки не принимал на провоцирование
переполнения плевался ассертами а не тупо с ума сходил как GArray )

то что работал он только с примитивными типами это да ну я тогда от си фанател
и с цепепе только знакомился сейчас бы может что получше написал ...
Re[8]: integer overflow
От: B0FEE664  
Дата: 10.11.11 13:16
Оценка:
Здравствуйте, Masterkent, Вы писали:

G>>3 + 0xff = 2 для беззнаковых 8-ми битных интов. Не?


M>При сложении двух беззнаковых 8-битных целых каждый операнд перед вычислением суммы будет преобразован к int (в представлении которого по стандарту должно быть не менее 16 бит), и результат вычисления суммы также будет иметь тип int. Естественно, при таком раскладе ни о каком переполнении не может быть и речи (пока результат явным образом не пытаются запихнуть в 8-битное целое, но это уже другой разговор).


Не совсем понятно почему "результат вычисления суммы также будет иметь тип int",
Ведь:

3.9.1.4 Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number
of bits in the value representation of that particular size of integer.

значит при n = 8:
3 % 256 + 255 % 256 => 258 % 256 = 2 % 256 = 2
3 % 256 = 3
2 < 3
=> "owerflow"
И каждый день — без права на ошибку...
Re[9]: integer overflow
От: Masterkent  
Дата: 10.11.11 17:08
Оценка:
B0FEE664:

G>>>3 + 0xff = 2 для беззнаковых 8-ми битных интов. Не?


M>>При сложении двух беззнаковых 8-битных целых каждый операнд перед вычислением суммы будет преобразован к int (в представлении которого по стандарту должно быть не менее 16 бит), и результат вычисления суммы также будет иметь тип int. Естественно, при таком раскладе ни о каком переполнении не может быть и речи (пока результат явным образом не пытаются запихнуть в 8-битное целое, но это уже другой разговор).


BFE>Не совсем понятно почему "результат вычисления суммы также будет иметь тип int"


Clause 5 p.9:

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

— If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
— If either operand is of type long double, the other shall be converted to long double.
— Otherwise, if either operand is double, the other shall be converted to double.
— Otherwise, if either operand is float, the other shall be converted to float.
— Otherwise, the integral promotions (4.5) shall be performed on both operands. [Footnote: As a consequence, operands of type bool, char16_t, char32_t, wchar_t, or an enumerated type are converted to some integral type.] Then the following rules shall be applied to the promoted operands:
— If both operands have the same type, no further conversion is needed.
[...]

5.7 Additive operators — p.1:

The additive operators + and — group left-to-right. The usual arithmetic conversions are performed for operands of arithmetic or enumeration type.

4.5 Integral promotions:

1 A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

2 A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted to a prvalue of the first of
the following types that can represent all the values of its underlying type: int, unsigned int, long int,
unsigned long int, long long int, or unsigned long long int. If none of the types in that list can
represent all the values of its underlying type, a prvalue of type char16_t, char32_t, or wchar_t can be
converted to a prvalue of its underlying type.

4.13 Integer conversion rank — p.1:

Every integer type has an integer conversion rank defined as follows:
— No two signed integer types other than char and signed char (if char is signed) shall have the same rank, even if they have the same representation.
— The rank of a signed integer type shall be greater than the rank of any signed integer type with a smaller size.
— The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.
— The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.
— The rank of any standard integer type shall be greater than the rank of any extended integer type with the same size.
— The rank of char shall equal the rank of signed char and unsigned char.
— The rank of bool shall be less than the rank of all other standard integer types.
— The ranks of char16_t, char32_t, and wchar_t shall equal the ranks of their underlying types (3.9.1).
— The rank of any extended signed integer type relative to another extended signed integer type with the same size is implementation-defined, but still subject to the other rules for determining the integer conversion rank.
— For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has greater rank than T3, then T1 shall have greater rank than T3.

Из всего этого с учётом требований ко вместимости int следует, что о каких бы 8-битных целых ни шла речь, они при сложении (в том виде, как это было представлено выше) неизбежно будут "продвинуты" до int и результирующее значение также будет типа int.
Re[8]: integer overflow
От: Sir-G  
Дата: 11.11.11 06:12
Оценка:
Здравствуйте, Masterkent, Вы писали:

M>пока результат явным образом не пытаются запихнуть в 8-битное целое, но это уже другой разговор.

Верно ли, что гарантируется, что когда мы запихнем 3+255=258 типа int в 8-битный unsigned char, то все же получим 2?
Re[9]: integer overflow
От: Masterkent  
Дата: 11.11.11 15:39
Оценка:
Sir-G:

M>>пока результат явным образом не пытаются запихнуть в 8-битное целое, но это уже другой разговор.

SG>Верно ли, что гарантируется, что когда мы запихнем 3+255=258 типа int в 8-битный unsigned char, то все же получим 2?

Да.

С++11 — 4.7 Integral conversions — p.2:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2ⁿ where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.