Блог пользователя ofi

Автор ofi, история, 8 лет назад, По-английски
vector<int> v;

int f()
{
	v.push_back(-1);
	return 1;
}
int main()
{
	v.push_back(0);
	cout<<v[0]<<endl;
	v[0]=f();
	cout<<v[0]<<' '<<v[1]<<endl;
		
	return 0;
}

expected output:

0

1 -1

output:

0

0 1

  • Проголосовать: нравится
  • +49
  • Проголосовать: не нравится

»
8 лет назад, скрыть # |
 
Проголосовать: нравится +51 Проголосовать: не нравится

When evaluating v[0]=f(); vector resizes from 1 to 2, reallocation happens, but the left-hand side address is evaluated before reallocation happens, so you perform an assignment to the memory region that is not a content of a vector any more.

The order of evaluation of sides in an assignment operator is not defined, thus you have UB.

»
8 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

The following modification produces the expected output.

int w = f(); v[0] = w;

Global variables should be used carefully so as to avoid such unexpected side effects.

Best wishes

»
8 лет назад, скрыть # |
 
Проголосовать: нравится +8 Проголосовать: не нравится

Thanks, it really was usefull.