Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was working on a C++ code, which for some unknown reason, does not terminate by Ctrl + C.

The below code is a reduced version of the code I was working on and it has the same issue. Moreover, if I don't take an input for M (remove '>>M') or remove vector a(n) or initialize the size of vector a by an integer literal instead or compile the code without -O3 compiler flag, the program terminates by Ctrl + C as expected.

Operating System: Windows 10
Compiler: MinGW
Compilation command: g++ -O3 -std=c++14

C++
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int N,M;
    cin>>N>>M;
    vector a(N);
}


What I have tried:

I have no idea why this behaviour is happening and cannot find any resource to explain the same.
Posted
Updated 5-Nov-19 21:10pm

I strongly suspect this is a bug in the compiler's code optimization: M isn't read by the program, so the compiler will try to eliminate code referring to it - maybe it messed up this optimization because the statement cin>>N>>M internally translates into a nested function call: operator>>(operator>>(cin, N), M). Optimizing M away out of that nested call could be tricky for the compiler with regard to how the state of cin is affected. - maybe it's left in a strate where it eats all input, including ^C ...

Disabling optimization, forcing a read on M later in the program, or splitting the input line in two all could help avoiding this error, but since I don't have MinGW I can't test that.

While of course you can never be sure to avoid a compiler error that you don't know about, I've found that, if a program doesn't do what it's supposed to, it's best to simplify the code statements and see if that helps.
 
Share this answer
 
v2
On my Linux box (Ubuntu 18), the following program
C++
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int N,M;
    cin>>N>>M;
    vector<int> a(N);
}

compiled with the g++ -O3 -std=c++14 (g++ 7.4.0) behaves as espected.
 
Share this answer
 
Comments
Stefan_Lang 5-Nov-19 10:53am    
Same for vc14.0 on W10. Sounds like a compiler code optimization issue to me.
Might be a debugger issue, see: Workaround for GDB Ctrl-C Interrupt | MinGW[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900