cout giving Runtime Error - c++

#include "iostream"
using namespace std;
int main(int argc, char const *argv[])
{
int n=100000;
int cost=6;
for (int i = 1; i <= n; ++i)
{
cout<<cost<<endl;
}
return 0;
}
The above program when compiled and run on ideone.com (online g++ compiler which uses SPOJ compiler) gives a Runtime Error. When the cout line is commented out, the program runs successfully. Can someone point out the reason for the same?

As pts pointed it out in his comment, ideone.com has a limit to the number of bytes you can print out. If you change n to 10000, the code runs fine.
The maximum n value that won't give compile error is 2^15 = 32768.
If you look carefully, you can see it terminates with signal:25, SIGXFSZ. You can take a look at this page to learn what signals mean.
SIGXFSZ 25 File size limit exceeded (4.2 BSD)

Theoretically this could overflow if int is two bytes on your platform (which the standard allows). But most likely the error is due to output size limits at ideone.com. Do learn to interpret error messages: they are your friends and are as least as important as desired program output.

Related

Pre increment and post increment when put together on a single variable like this (++i)++, it works in c++ but not in c

I initialized a variable i with a value 3, then put a statement (++i)++ in my code. But, in C, it is showing an error "lvalue required as increment operand". But, if I put this similar code in c++, it works and showing double increment with an output 5. However, one of my friends tried on his compiler using c and it gave an output 4.
//using c
#include <stdio.h>
int main()
{
int i=3;
(++i)++;
printf("%d",i);
return 0;
}
//using c++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i=3;
(++i)++;
cout << i << endl;
return 0;
}
I am using GNU GCC compiler.
This is known to be undefined behavior. Syntactically this program is correct in C++, and the compiler produces some binary code... but the standard allows it to produce ANY code, even something that returns 100 or formats your disk. In real situations you may observe very strange abnormal scenarios, for example the compiler can drop the whole code after your (++i)++ statement, because the standard allows it to do whatever it wants right after the program enters into the status of UB. In your case that would mean that there would be no output at all (or the program would print "Hello World" instead of the integer value).
I believe that you are just conducting an experiment. The result is: both your compiler and your friend's are correct.

Explanation for weird behavious when ios::sync_with_stdio(0) and cin.tie(0) are written inside loop

The input I am giving is
5
1 1 1 1 1
Can someone explain me this behaviour?
I actually found this during a online competitive programming contest. I was getting wrong answer verdict. While on my computer it worked fine, online IDEs gave a runtime error (Bus error). So I tried the below code (which is actually different than the original problem solution) but the principle I guess remains the same. If I get enough insight from this explanation, I might also understand the original solution errors. If not I will put additional queries.
#include <iostream>
using namespace std;
int main()
{
int t, a = 9;
cin >> t;
while(t--)
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> a;
cout << a;
}
}
The below code when run on online ide gives output as:
99999
(I tested on codechef.com/ide and ide.geeksforgeeks.org)
While on my computer terminal (Ubuntu, g++) it gives output as:
11111
(This is true when I pass a input file to it or manually enter data in terminal)
This weird behavior is only when the two statements are inside the while loop. When written above the while loop, the output is as expected.
According to cppreference:
If [ios::sync_with_stdio] is called after I/O has occurred on the standard stream, the behavior is implementation-defined: implementations range from no effect to destroying the read buffer.
So you should not be calling this function inside your loop. Instead, just call it once at the start of main:
https://wandbox.org/permlink/fhpRNUGCXDef1bw4

Why I am getting garbage(unwanted) output here?

Whenever I am writing this following code, I am getting garbage(unexpected) output in some online compiler, but if I use code block then getting satisfied output. So my question is why I am getting this type of output?
for example, if I input
5 7
+ 5
- 10
- 20
+ 40
- 20
then I am getting
22 1
in the code block. But in the online compiler, it's something else.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int have, n, i;
int kid=0;
cin>>n>>have;
int line[n];
for(i=0;i<n;i++)
{
cin>>line[i];
if(line[i]>=0)
have+=line[i];
else
{
if(have>=abs(line[i]))
have+=line[i];
else
kid++;
}
}
cout<<have<<" "<<kid<<endl;
}
The main problem I can see in your code is this:
int line[n];
This is known as a VLA (Variable Length Array) and it is not supported in C++. It is valid in C. Most compilers still allow this behaviour due to the fact that C++ is based on C, but it is not valid C++ code. In a previous question, I found out that clang supports designated initializers, when gcc and vc++ did not. The reason is because some compilers like clang, support c99-extensions by default. My point is that just because the code compiles, it doesn't mean it's always right.
If you compile with the -pedantic argument, you will see that the compiler is warning you about this being a C99 feature. Have a look at the rextester example here. From the comments below, using -pedantic-errors in the compiler flags, will prompt an error.
If you know the size of the array before run-time, then you should use a static array int line[4];, but if you don't then you need to use a dynamic array. std::vector is essentially a dynamic array that also handles memory for you. It's easy to use and very efficient. std::vector<int> line;
You can read more about the vector container here: http://www.cplusplus.com/reference/vector/vector/
Btw, I tried your code in rextester, ideone and repl.it and I got the same results: 22 1. I think what you are witnessing it undefined behaviour.
Also, you can qualify int n with constexpr and it'll be fine.
constexr int n = 200;
int line[n]; //now it's ok.
But this again means that you know the size of the array at compile time.

Return value of cin not 0 upon pressing Enter

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int i=0;
int a[100];
while(cin>>a[i]){i++;}
cout<<i;
return 0;
}
This code is used for getting an array input without knowing its size previously. Note that I used a[100] since the bounds are given and the number of elements does not exceed 100.
This worked fine in all of the compilers except for Code::Blocks, where the loop goes on even after pressing ENTER. Shouldn't the condition of the while loop be false upon pressing ENTER on the keyboard on all compilers?
Is there any workaround for this or any other way to get array inputs without knowing its size?
The Enter key tells the terminal to send the input to your program, nothing else. If you want to terminate the input you need to send end-of-file character.
On POSIX systems (like Linux and macOS) end-of-file is usually Ctrl-D, on Windows it's usually Ctrl-Z (on an empty line and possibly pressing Enter after).
And as you should have guessed from the above, this has nothing to do with the compiler, but rather the environment (most notably the operating system).
On a slightly related note, your code
for getting an array input without knowing its size previously
is seriously flawed. What happens if the user inputs more than 100 values? Then you will go out of bounds.
Better learn about std::vector quickly.
maybe below this code will help
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int i=0;
int a[100];
while(cin>>a[i]){
i++;
if(cin.get()=='\n') break;
}
cout<<i;
return 0;
}
here you must have to aware about if user enter will enter value more then 100
as per your array a[100] then your logic or above program will not work and go in infinite loop

C++ printing extremely faster than C

I am taking part in a small programming competition online. Basically what I do is solve a task, write an algorithm and send my code to be automatically evaluated by the competition holder's server.
The server accepts a wide variety of programming languages. All the tasks basically require the program to take input from the terminal and output a correct to the terminal as well. So on the competition holder's website I noticed that one of the languages they support is C++ and they use g++ to compile it. Well, since I'm not that fluent in C++ as opposed to C I thought I would return my answers in C.
This worked great for the first task. However in the second task I constantly hit the limit set for the execution time of the program (2 seconds)
This is my C code:
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <stdlib.h>
uint8_t get_bit(uint64_t k) {
...
}
int main(int argc, char *argv[]) {
uint64_t n;
uint64_t k;
scanf("%u", &n);
uint64_t i;
for (i = 0; i < n; i++) {
scanf("%u", &k);
printf("%d\n", get_bit(k));
}
return 0;
}
So my algorithm is defined in get_bit.
The server runs 3 different tests on my program, with different values, mostly increasing to make the program run longer.
However, this code in C failed the tests due to taking more than 2 seconds to run. Trying different solutions for hours with no avail, I finally tried to submit my code as C++ with a little different printing methods.
Here is my C++ main (the rest of the program stayed mostly the same):
int main(int argc, char *argv[]) {
uint64_t n;
uint64_t k;
cin >> n;
uint64_t i;
for (i = 0; i < n; i++) {
cin >> k;
cout.operator<<(get_bit(k)) << endl;
}
return 0;
}
And when I submitted this code, all the tests ran perfectly in just a few hundred milliseconds each. Note that I did not alter my algorithm in get_bit but only the printing.
Why is printing in C++ so much faster than in C? (in my case up to 10x faster)
If it's possible, how can I achieve these speeds in C as well? As you might probably notice, I am not fluent in C++ and the previous code is mainly copy paste. For this reason I would much rather prefer to program in C.
Thank you in advance.
It is probably because your code is may be (see comments) incorrect. You cant use %u with scanf and 64-bit integer.
Check the third table here http://www.cplusplus.com/reference/cstdio/scanf/ . You should use sth like %llu.