Simple C++ loop takes up entire RAM - c++

I was doing some coding on C++ just to get used to its syntax (I'm Java developer). However, I've written the code below and it takes up the entire RAM in seconds, the more free RAM you have, the faster program takes it up. When I uncomment the cout method to print current string at the end of every loop, it starts to take RAM up drastically slower (10-15mb in a minute). Does printing operation slows the cycle that much, or is there another reason?
#include <iostream>
#include <list>
using namespace std;
int main() {
string inf;
list<string> myList;
for(;;){
inf += "___ ";
myList.push_back(inf);
//cout << inf;
}
}

for(;;) is an infenite loop.
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Since your statement 2 is empty it defaults to true, so this loop keeps on running.

The reason why this is happening is simply fact that i/o operations are really slow compared to appending list. Therefore this seemed to be work "okay". This loop is just infinite, never stops.

you for(;;) loop is infinite and as such mylist is continually expanded until it has filled your entire RAM. The execution time of appending simple symbol into the list is extremely low, so your RAM is filled extremely fast. When cout is added to the loop, the loop has to output before it can append more to mylist. The execution time of outputting takes significantly longer than appending and as such the time between loops is slowed. This in turn means your RAM will be filled more slowly.

Related

The While loop is not terminating even i tried decrementing t

The Problem of the Solution is that first line will contain total no. of Input and the next line will take three integer and then we have to calculate the result based on the input.So the Problem with my Solution is that the While Loop is Not Terminating.
I have Checked the code several times and thinks that this is happening because of the conditional statement and because of if-else the --t statement is not getting executed.So,what modifications should i do to make the program terminate after t input.
#include<iostream>
using namespace std;
int main()
{
int t{0};
cin>>t;
while(t)
{
double h{0},c{0},t(0);
cin>>h>>c>>t;
if(h>50 and c<0.7 and t>5600)
cout<<"10\n";
else if(h>50 and c<0.7)
cout<<"9\n";
else if(c<0.7 and t>5600)
cout<<"8\n";
else if(h>50 and t>5600)
cout<<"7\n";
else if(h>50 or c<0.7 or t>5600)
cout<<"6\n";
else
cout<<"5\n";
--t;
}
return 0;
}
I expect the Program to terminate after t input but it is not happening.
Outside the loop you have
int t{0};
And inside the loop you have
double h{0},c{0},t(0);
You have two different and distinctive variables t that shadows each other. And inside the loop when you do --t you decrement the variable inside the loop, not the one you use for the looping condition.
You solve this by using descriptive names for your variables, instead of short one-letter names.

Comparing 2 source codes with same logic

This is my code for "Life, the Universe, and Everything" at hackerearth
Why "my solution" is slower than the "best solution" even though the logic
used is same!
In fact I think my logic should be faster because I printed the answer when n!=42 but the "best solution" has to first check for n==42 and then insert element in array (executing the 'else' part).
Please tell me why "best solution" is faster.
my solution :-
#include <iostream>
using namespace std;
int main()
{
int n;
while(1)
{
scanf("%d",&n);
if(n!=42)
{
printf("%d\n",n);
}
else
break;
}
return 0;
}
Time Taken: 1.010669 seconds
---------------------------------------------------------
best solution:-
#include <iostream>
using namespace std;
int main()
{
int n,a[10001],i=0,j;
while(1)
{
cin>>n;
if(n==42)
break;
else
a[i++]=n;
}
for(j=0;j<i;j++)
cout<<a[j]<<endl;
return 0;
}
Time Taken: 1.004222 seconds
scanf and printf are extremely expensive functions in terms of processing. They have to interpret the format string (where you write "%d" there could be a huge variety of complex format placeholders). By the time this alone is done, the other solution has probably done it's processing already. The source code for the scanf function would be several hundred lines of code, and printf too.
On the other hand, in the best solution the compiler knows the expected types already and has to deal with a lot less computing that is done at run time, so the conversion from input string to integer and vice versa is far more effective.
haven't tested it yet, but your output include twice as much output to console.
for each number "best solution" prints, you add a \n too.
more characters = more time to process your stdout buffer.

3-way mergesort stackoverflow error in c++

hi guys can anyone tell me what's wrong with my 3-way mergesort code?the code I wrote can only sort 4 numbers if you give it more than 4 numbers(by changing size) it ends up with stack overflow error,here is the code:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
const int size=4;
vector <int> s(size);
void merge(int,int,int);
void mergesort(int,int);
int main(){
for(int i=0;i<size;i++){
cout<<"enter number "<<i+1<<":";
cin>>s.at(i);
}
system("CLS");
cout<<"here are the unsorted numbers:\n";//prints the input values so U can see'em
for(int j=0;j<size;j++)
cout<<s.at(j)<<".";
mergesort(0,size-1);//calls mergesort
cout<<"\nhere are the sorted numbers:\n";
for(int j=0;j<size;j++)
cout<<s.at(j)<<".";
cin.get();
cin.get();
return 0;
}
void merge(int low,int one_third,int high){
int i=low;
int j=one_third+1;
int k=0;
int length=(high-low)+1;
vector <int> u(length,0);
if(k<length){
while((i<=one_third)&&(j<=high)){
if(s.at(i)<=s.at(j)){
u.at(k)=s.at(i);
i++;
k++;
}//end for
else{
u.at(k)=s.at(j);
j++;
k++;
}//end elseif
}//end while
if(j>high)
while(i<=one_third)
{
u.at(k)=s.at(i);
i++;
k++;
}
if(i>one_third)
while(j<=high)
{
u.at(k)=s.at(j);
j++;
k++;
}
for(int n=low;n<k;n++)
s.at(n)=u.at(n);
}
}//end if
void mergesort(int low,int high){
if(low<high){
int one_third=(high-low)/3;//division,it's 3-way mergesort so obviously it's divided by 3
int two_third=2*one_third;
mergesort(low,one_third);
mergesort(one_third+1,two_third);
mergesort(two_third+1,high);
merge(low,one_third,two_third);
merge(low,two_third,high);
}//end if
}
at this point I guess I'm done thinking,Any answer/idea would be appreciated.
Here's a partial inspection of your code. I believe there is an issue debugging a 3 way merge sort with 4 values. You should use more values, such as 6 or 7.
Spaces not tabs for StackOverflow
I'll take a guess that the indentation is because you use tab characters in your code and pasted directly. You'll want to expand the tabs in your next post.
Precompiled Headers
Is your project huge? Does it significantly reduce the build time when you change a header or modify the source code?
I find that stdafx usually is more of a hassle and the time spent resolve defects it causes negates any potential savings by having a precompiled header.
Function prototypes should use named parameters
Can you tell the purpose of the different parameters in your declaration of merge and mergeSort?
Ambiguity breeds defects. 'nuff said.
Main function declared wrong.
The main function always returns an int to the operating system, always. The OS can ignore it.
This mechanism is so that script files can execute your program and test for errors.
Readability prevents defects
Invest in spaces around operators. The time saved by sacrificing spaces is negligible. The debugging time saved by having easy to read code is tremendous, especially when having other people review or inspect your code.
Use intermediate variables
Intermediate variables help clarify your program. They don't cost memory when you tell the compiler to optimize. During debugging, they can help show values during calculations.
The typical idiom for reading into a vector is:
int value;
cin >> value;
s.push_back(value);
The at method may have an overflow issue (or at least your not checking for out of bounds issues). The push_back method will cause the vector to expand as necessary.
Meaningful variable names reduces defects
The variable s has no meaning. Something like original_values or number_container are more descriptive. And again, variable name lengths have nothing to do with improving performance. Readable names help reduce the defects injected.
Not checking state of cin
If I enter "Lion" in response to your 2nd prompt, what will be in the 2nd slot of the array?
Don't trust the Users, they aren't perfect.
Don't clear the screen
It may contain useful data, such as the actual numbers entered. So when you are debugging, and want to know what the User actually typed in, it will be lost and gone forever.
Why cin.get twice?
You are asking the User for input without prompting. And twice. Bad Karma between your program and the User.
See cin.ignore if you want to ignore characters until a specific one is received. Something like this perhaps:
cout << "Paused. Press Enter to continue.\n";
cin.ignore(100000, '\n');
Magic numbers
In function mergesort, you use the numbers 2 and 3. Why? What's their purpose?
Redundant comments
Most programmers realize that the '/' character in a math expression is division. The comment is redundant.
Also, why divide by 3? It's a nasty number. Do you realize you are performing integer division and your product will be truncated? For example: 1/3 == 2/3 == 0.
USE A DEBUGGER
Lastly, a lot of your program's functionality can be verified easier and quicker by using a debugger. A debugger allows you to execute a statement and see the variable values. You can set breakpoints to stop execution at different places. It's a worthwhile educational investment, start now.
A "classic" 3 way merge sort merges runs 3 at a time, alternating between a source and destination array (or vector or list). The code needs to perform up to 3 compares in order to determine the "smallest" of 3 values from each of the 3 runs, then move the smallest value from it's corresponding run to the destination array. The code also has to handle the case where the end of a run is reached, leaving only 2 runs to merge, then the case where the end of the second run is reached, in which case the rest of the third run is moved to the destination array.
For a ram based sort, I'm not sure this is any faster than a normal 2 way merge. For an external sort, with multiple devices or very large read and writes, then a k way merge with k up to 12 or 16 will be faster.

Returning from a function enters an infinite loop Visual Studio 2012

I am trying to test the speed of various pointer speeds and ran into a really weird problem. When allocating for raw pointers, it runs fine. (There is a memory leak, but that isn't the problem.) When I run the second test with shared_ptr, It runs the fill fine, prints the log and then when it returns, it enters an infinite loop. It appears the ref count is garbage, but I'm doing everything by value.
#include <memory>
#include <vector>
#include <functional>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <Windows.h>
using namespace std;
static const int TOTAL = 1000000;
int* newTest(int i)
{
return new int(i);
}
shared_ptr<int> sharedTest(int i)
{
return shared_ptr<int>(new int(i));
}
template <typename T>
pair<int, vector<typename T::result_type>> Fill(T fn)
{
unsigned long start = GetTickCount();
vector<typename T::result_type> vec;
vec.reserve(TOTAL);
for(int i = 0; i < TOTAL; i++)
{
vec.push_back(fn(i));
}
unsigned long end = GetTickCount();
return make_pair(end - start, move(vec));
}
template <typename T>
void Test(T fn, string name)
{
vector<typename T::result_type> newTest;
int milliseconds = 0;
tie(milliseconds, newTest) = Fill(fn);
cout << "Fill " << name << " Took " << milliseconds << " milliseconds." << endl;
}
int main()
{
function<int*(int)> fn1 = newTest;
Test(fn1, "Raw Ptr");
function<shared_ptr<int>(int)> fn2 = sharedTest;
Test(fn2, "Shared New");
return 0;
}
OK. It appears I have asked a stack overflow question on Stackoverflow....
When I set TOTAL to 10000 it's fine. So, is that just a symptom of something else or do I need to increase my stack size?
Edit from comment:
Tavison: OK. after several minutes it ended. You're right about not being an infinite loop. But, 1043 ms to new and many minutes to delete makes it hard to justify using them. This is not a result I would expect.
There is no infinite loop, you're just being impatient. It's taking time to free all the shared_ptr's.
To be able to claim there is an infinite loop, you need to actually step into the code and take a look. Check that there is some loop somewhere with a condition that will never change. This is not the case here.
Lower your TOTAL, for example, and verify it actually ends. Having more of these will not magically introduce an infinite loop at some number, so if it works at a lower number, it works at a higher one.
Or, don't allocate ints; allocate some test struct that outputs "bye" (along with some counter) when its destructing, and you'll see "post"-test that they're all being deleted. (Of course, performing IO will increase the destruction time, but the point is to verify a condition is moving towards stopping a loop.)
Also, you can cut the allocations in half by using return make_shared<int>(i); rather than newing the int yourself and putting it into a shared_ptr. Always use make_shared.
Lastly, this is only slow if you have a debugger attached, because it'll, well, debug your memory usage. That is, verify that what you're deleting is sensible to delete, isn't corrupting anything, etc.
And for the love of programming use four spaces to indent, not two.
If you run the code in debug or release with debugging, you'll get a debug heap that can be used to track memory errors. Freed memory is filled with debug patterns when this happens, so the code will run slower. Running the code without debugging from Visual Studio ends in less than 200 milliseconds.

execution order of loops in C

this is probably a very noob question but I was what the result of this would be:
int someVariable = 1;
while (callFunction(someVariable));
if (someVariable = 1) {
printf("a1");
} else {
printf("a2");
}
callFunction (int i) {
while (i< 100000000) {
i++;
}
return 0;
}
so when you hit the while loop
while (callFunction(someVariable));
does a thread wait at that loop until it finishes and then to
if(someVariable == 1) {
printf("a1");
} else {
printf("a2");
}
or does it skip and move to the if condition, print "a2" and then after the loop has finished goes through the if condition again?
UPDATE: This isn't ment to be valid c code just psuedo, maybe I didn't word it right, basically what I'm trying to figure out is what the different between a loop like while (callFunction(someVariable)); is vs
while (callFunction(someVariable)){}
i also changed the bolded part in my code i.e ** int someVariable = 1; **, I was doing an endless loop which wasn't my intention.
The code inside a function is executed sequentially, by a single thread. Even if you send an other thread to your function it will execute it sequentually as well.
This is true to 99% of programming languages now days.
UPDATE
basically what I'm trying to figure out is what the different between a loop like while (callFunction(someVariable)); is vs while (callFunction(someVariable)){}
No practical difference. ; delimits an empty statement, { } is a scope without statements. Any compiler can be expected to produce identical code.
Of course, if you want to do something in each iteration of the loop, { } creates a "scope" in which you can create types, typedefs and variables as well as call functions: on reaching the '}' or having an uncaught exception, the local content is cleaned up - with destructors called and any identifiers/symbols use forgotten as the compiler continues....
ORIGINAL ANSWER
This...
callFunction(int i){
while (i< 100000000){
i++;
}
return 1;
}
...just wastes a lot of CPU time, if the compiler's optimiser doesn't remove the loop on the basis that it does no externally-visible work - i.e. that there are no side-effects of the loop on the state of anything other that "i" and that that's irrelevant because the function returns without using i again. If always returns "1", which means the calling code...
while (callFunction(someVariable));
...is equivalent to...
while (1)
;
...which simply loops forever.
Consequently, the rest of the program - after this while loop - is never executed.
It's very hard to guess what you were really trying to do.
To get better at programming yourself - understanding the behaviour of your code - you should probably do one or both of:
insert output statements into your program so you can see how the value of variables is changing as the program executes, and whether it's exiting loops
use a debugger to do the same
Your code contains an endless loop before any output:
while (callFunction(someVariable));
Did you mean for the ; to be there (an empty loop), or did you
mean something else? Not that it matters: callFunction
always returns 1, which is converted into true. (If you
really want the loop to be empty, at least put the ; on
a separate line where it can be seen.)
If you do get beyond the while (because you modify some code
somewhere), the if contains an embedded assignment; it's
basically the same as:
if ( (someVariable = 1) != 0 )
Which is, of course, always true. (Most C++ compilers should
warn about the embedded assignment or the fact that the if
always evaluates to true. Or both.)
If your loop completes (it would be sequentially yes, if you fix it), it will print 'a1', since you're doing an assignment in the if, which will always return 1, which evaluates to 'true' for conditionals.