Code Crashes Immediately After Running - c++

Even at the bare minimum of 10 numbers to input, I get no errors but my code crashes immediately on running. I was also wondering, what should I do if I have a question similar to another question that I've already asked, but on another new problem?
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime==true) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
}
}
I get no errors but the compiled code crashes immediately.
I changed it to
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a.push_back(2);
for (double i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
return a.size();
}
}
I addressed all of your problems. It still returns no errors and still crashes.

What makes you think you can do this?
vector<int> a;
a[1]=2;

vector<int> a;
a[1]=2;
You can't access a[1] until you've reserved space for it. You should probably use a.push_back(2) to append 2 to the end of a.
You have declared primer to return int, yet it returns nothing. Either make it void or return the number of primes.
i/a[ii]==floor(i/a[ii]) isn't going to do what you expect. i/a[ii] performs integer division. You should cast i to double before dividing.
if (prime==true) can be changed to simply if (prime), no need to compare a boolean to true.
Please improve your coding style. Use proper indentation and more commonly used variable names: i, j, k instead of i, ii, iii.

Here is another bug:
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
return a.size();
}
My understanding is that you can only return once from a function, main included. The execution will not loop here because of the return statement.
Did you really want a return statement inside a for loop?

Related

C++ alternative to singleton design when a function-only class needs to be initialize at least once?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <random>
#include <map>
#include <math.h>
#include <cstring>
using namespace std;
class MathClass {
private:
size_t current_capacity;
double* logfact;
bool inited = false;
MathClass() {
current_capacity = 0;
logfact = new double[1];
logfact[0] = 0;
}
void calculateLogFact(int n) {
if (current_capacity >= n) return;
double* newLogfact = new double[n+1];
for (int i=0; i<=current_capacity; i++) newLogfact[i] = logfact[i];
for (int i=current_capacity+1; i<=n; i++) newLogfact[i] = newLogfact[i-1] + log(double(i));
delete[] logfact;
logfact = newLogfact;
}
double factorial(int n) {
cout << "n = " << n << "\n";
calculateLogFact(n);
for (int i=0; i<=n; i++) cout << int64_t(round(exp(logfact[i]))) << " ";
cout << "\n";
return exp(logfact[n]);
}
public:
static double factorial2n(int n) {
static MathClass singleton;
return singleton.factorial(2*n);
}
};
int main(int argc, char** argv)
{
cout << MathClass::factorial2n(10) << "\n";
return 0;
}
My library need to use an expensive function that needs to be initialized once before use (to pre-calculate some expensive values so that we don't have to calculate them every time). Currently, I use the singleton method above for this.
However, there are 2 problems:
Multi-threading: this will cause race conditions if 2 different threads call this function.
People don't like singleton
Other problems that I'm not aware of
What other design can I use to solve this problem? Pre-computing values is a must since this function needs to be fast.
I agree with comments: Why hide the fact that MathClass caches results from the user? I, as a potential user, see no real benefit, rather potential confusion. If I want to reuse previously cached results stored in an instance I can do that. You need not wrap the whole class in a singleton for me to enable that. Also there is no need to manually manage a dynamic array when you can use std::vector.
In short: The alternative to using a singleton is to not use a singleton.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <random>
#include <map>
#include <math.h>
#include <cstring>
using namespace std;
class MathClass {
private:
size_t current_capacity;
std::vector<double> logfact;
bool inited = false;
void calculateLogFact(int n) {
if (logfact.size() >= n) return;
auto old_size= logfact.size();
logfact.resize(n);
for (int i=old_size; i<n; i++) logfact.push_back(logfact.back() + log(double(i)));
}
double factorial(int n) {
cout << "n = " << n << "\n";
calculateLogFact(n);
for (int i=0; i<=n; i++) cout << int64_t(round(exp(logfact[i]))) << " ";
cout << "\n";
return exp(logfact[n]);
}
public:
MathClass() {
logfact.push_back(0);
}
double factorial2n(int n) {
return factorial(2*n);
}
};
void foo(MathClass& mc) { // some function using previously calculated results
std::cout << mc.factorial2n(2);
}
int main(int argc, char** argv)
{
MathClass mc;
cout << mc.factorial2n(10) << "\n";
foo(mc);
}
I am not sure if the maths is correct, I didn't bother to check. Also inited and most of the includes seem to be unused.
Concerning "Multi-threading: this will cause race conditions if 2 different threads call this function." I would also not bother too much to bake the thread-safety into the type itself. When I want to use it single-threaded I do not need thread-safety, and I don't want to pay for it. When I want to use it multi-threaded, I can do that by using my own std::mutex to protect access to the mc instance.
PS: Frankly, I think the whole issue is caused by a misconception. Your MathClass is not a "function only" class. It is a class with state and member functions, just like any other class too. The "misconception" is to hide the state from the user and pretend that there is no state when in fact there is state. When using this class I would want to be in conctrol what results I can query because they are already cached and which results need to be computed first. In other words, I would provide more access to the class state, rather than less.

Why is in the following similar codes one giving runtime error and other is not

Well this is really weird
Consider the following two codes :-
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
for(int i = 0; i < 5; i++)
{
*ptr[i]=a[i];
}
for(int i = 0; i < 5; i++)
{
cout<<*(ptr[i]);
}
}
AND
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
*ptr[2]=a[2];
*ptr[3]=a[3];
*ptr[4]=a[4];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
cout<<*(ptr[2])<<endl;
cout<<*(ptr[3])<<endl;
cout<<*(ptr[4])<<endl;
}
The first one gives runtime errorr , while the seconde one gives 1 ,2 ,3 ,4 ,5 output , I can't find the difference between the two codes , can anyone help me to find the difference .
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
}
the above code runs fine and gives output 1, 2
but
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
*ptr[2]=a[2];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
cout<<*(ptr[2])<<endl;
}
this code gives runtime error on codeblocks(gcc) , I am just getting more confused
I have both runtime errors.
The result of recoding with the pointer variable below.
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
for(int i = 0; i < 5; i++)
{
ptr[i]=&a[i];
}
for(int i = 0; i < 5; i++)
{
cout<<*(ptr[i]);
}
}
It is already established that
*ptr[0] = a[0];
with unallocated pointer is undefined behavior.
The solution
ptr[0] = &a[0];
is also already given. This works, but it is limited because now, the ptr array is tied to a, which you not always want. In that case you might want
ptr[0] = new int(a[0]);
This initializes the array with values from a but keeps it independent. However, this introduces manual memory management and this can become tricky in more complex code (memory leaks, double deallocations, dangling pointers), so a more C++ like solution would be (assuming the pointers point to something more interesting than an integer, because now there seems to be no need for pointers).
#include <memory>
#include <vector>
#include <iostream>
int main() {
int a[]={1,2,3,4,5};
std::vector<std::unique_ptr<int>> ptrs;
for(auto i: a)
{
ptrs.emplace_back(std::make_unique<int>(i));
}
for(auto& i: ptrs)
{
std::cout << *i;
}
}

c++ program crashes before main

When I run my code below, the program crashes and the compiler message is Segmentation fault. I've searched for bugs in my code but I can't find any. My program doesn't even seem to enter main(), because I've tried using 'cout' to see where it crashes but I get no output, even when 'cout'-ing immedeately after main starts. Here is the code. Can someone tell me what the problem is?
#include <cmath>
#include <stdio.h>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct edge_t
{
int a,b,w;
};
bool comp(edge_t a, edge_t b)
{
if(a.w < b.w)
return true;
return false;
}
vector<int> parent;
int find_parent(int x)
{
if(parent[x] == x)
return x;
parent[x] = find_parent(parent[x]);
return parent[x];
}
void join(int a,int b)
{
parent[find_parent(a)] = find_parent(b);
return;
}
int mst(vector<edge_t> v)
{
sort(v.begin() , v.end() , comp);
for(int i=0;i<v.size();++i)
parent[i] = i;
int sum = 0;
for(int i=0;i<v.size();++i)
{
if(find_parent(v[i].a) != find_parent(v[i].b))
{
join(v[i].a, v[i].b);
sum += v[i].w;
}
}
return sum;
}
int main() {
cout<<"Hello?\n"; ///does not display anything QQ
int n,m;
scanf("%d %d",&n,&m);
parent.resize(n);
int p,q,r;
vector<edge_t> edges;
int s =0;
for(int i=0;i<m;++i)
{
scanf("%d %d %d",&p,&q,&r);
edge_t tmp;
tmp.a = p;
tmp.b = q;
tmp.w = r;
s+=r;
edges.push_back(tmp);
}
printf("%d\n", s - mst(edges));
return 0;
}
I'm using the online ide on hackerrank.com (I'm practising problems there).
Inside your mst function
for (int i = 0; i<v.size(); ++i)
parent[i] = i;
This assumes that parent has the same or more elements that v, and if that's not the case, your program crashes.
In the same function, you are calling find_parent and you haven't verified that a & b are lower than parent.size(), which would be fine if you checked that in your find_parent function, but you don't check it there either.
if (find_parent(v[i].a) != find_parent(v[i].b))
{
join(v[i].a, v[i].b);
sum += v[i].w;
}
Therefore, if find_parent gets invalid input, your program crashes
int find_parent(int x)
{
if (parent[x] == x)
return x;
}
Depending on your compilation environment if you have an instruction set enabled that your system does not support (e.g. AVX) crashes can occur prior to main (I have seen this happen on Windows with VC++). Try compiling with all optimisations switched off, for an "ancient" target architecture.
Depending on your platform, this could also be due to shared libraries not being found, although this seems less likely.
EDIT: Deleted the bit about cout since you have a end line character and main. That was an off thought.

Calculating prime numbers using multi threading

I started to work with threads recently and I tried to run a simple program that uses threads but I get really strange output.
The program writes the prime numbers in the given range with N(parameter to the function)number of threads into the file "PRIMES.txt", if the range <= 1000 the output is fine but if the range is bigger, then the output is something like :
‰‱′″‵‷ㄱㄠ″㜱ㄠ‹㌲㈠‹ㄳ㌠‷ㄴ㐠″㜴㔠″㤵㘠‱㜶㜠‱㌷㜠‹㌸㠠‹㜹ㄠ㄰ㄠ㌰ㄠ㜰ㄠ㤰ㄠ㌱ㄠ㜲ㄠㄳㄠ㜳ㄠ㤳ㄠ㤴ㄠㄵㄠ㜵ㄠ㌶ㄠ㜶ㄠ㌷ㄠ㤷... (much longer)
What would be the problem?
Here is my code :
threads.h :
#include <fstream>
#include <string>
#include <iostream>
#include <thread>
using namespace std;
void writePrimesToFile(int begin, int end, ofstream& file);
void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N);
threads.cpp :
#include "Threads.h"
#include <iostream>
#include <string>
#include <fstream>
#include <thread>
#include <mutex>
#include <vector>
mutex mtx;
void PrimesToFile(int begin, int end, ofstream& file)
{
bool isPrime;
string Primes;
int count = 0;
mtx.lock();
cout << "Thread is running" << endl;
for (int i = begin; i < end; i++)
{
isPrime = true;
for (int j = 2; j < i; j++)
{
if (i%j == 0)
isPrime = false;
}
if (isPrime)
{
Primes.append(to_string(i));
Primes.append(" ");
}
}
file.write(Primes.c_str(), Primes.length());
mtx.unlock();
}
void WritePrimesMultipleThreads(int begin, int end, string filePath, int N)
{
ofstream OP;
OP.open(filePath);
int lastPos = 0;
int destPos = end / N;
thread* TV = new thread[N];
for (int i = 0; i < N; i++)
{
TV[i] = thread(PrimesToFile, lastPos, destPos, ref(OP));
lastPos = destPos;
destPos += end / N;
}
for (int i = 0; i < N; i++)
TV[i].join();
}
Starting point :
#include "Threads.h"
#include <iostream>
#include <string>
#include <fstream>
#include <thread>
void main()
{
WritePrimesMultipleThreads(1, 10000, "PRIMES.txt", 5);
system("PAUSE");
}
Thanks!
Hours of debugging turned out to be in wrong implementation of std::ofstream. Just outputting at the beginning OP << "\n" solved the problem. Compiler is MSVC 2015 update 1. More about about it here. Additionally, you have resource leak, single threading when it is not really intended to, not efficient algorithm of finding primes in a range, compiling errors in your posted code, unnecessary writePrimesToFile function and header files in your header file, you're using using namespace std and may be more problems. I recommend you posting your code at codereview.stackexchange.com to make the code better, because solving this problem is not enough to solve the original problem.
EDIT: You need to flush the stream every time you done writing something.

Is there a way to display my prime number list output in 2 columns?

I am taking my first programming class and this is my first time posting. I have been able to find help on this site for previous projects when I got stuck, and I hope I am doing this right.
I have completed the program below to display only prime number between 0 and 100 for my intro to C++ class.
The only thing is it kinda bothers me that it is in a single column, I wanted to go the extra step and make it look all nice and display the numbers in a couple columns. I tried using "\t", but I can't get it to work right. Any ideas on what I might add to my code?
I think I could do it using an array but we have not covered it in class and I'm not supposed to use them yet.
the challenge was:
"Use the isPrime function that you wrote in Programming Challenge 21 in a program that stores a list of all the prime numbers from 1 through 100 in a file."
and here is my code:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;
bool isPrime(int);
int main()
{
static int num1=0;
cout<<"Listed below is all prime numbers from 1 through 100."<<endl<<endl<<endl;
do
{
num1++;
if (isPrime(num1))
{
cout<<num1<<endl;
}
}
while (num1<100);
cout<<endl;
return 0;
}
bool isPrime(int num1)
{
bool primeNum=true;
for (int i=2;i<num1;i++)
{
if (num1%i==0)
{
primeNum=false;
}
}
return primeNum;
}
Thanks in advance for any input,
Find cout.width()
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;
bool isPrime(int);
int main()
{
static int num1 = 0;
cout << "Listed below is all prime numbers from 1 through 100." << endl << endl << endl;
int column = 0; // column variable
int width = 10; // column width size
do
{
num1++;
if (isPrime(num1))
{
cout.width(width); // set column's width
cout << num1;
if (column == 1) { // if prime number is printed in column 2
cout << endl; // add new line
column = 0; // set column to first
}
else {
column++; // increase column index
}
}
} while (num1<100);
cout << endl;
return 0;
}
bool isPrime(int num1)
{
// error: your isPrime returns true when num1 is 1 or 2. change it
if (num1 == 1 || num1 == 2) return false;
// your isPrime
bool primeNum = true;
for (int i = 2; i<num1; i++)
{
if (num1%i == 0)
{
primeNum = false;
}
}
return primeNum;
}
I just realized the question asked for me to STORE the list to a file. So I rewrote and here is my new code:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
bool isPrime(int);
int main()
{
int num=0;
cout<<"This Program will store a list of only the prime numbers "<<endl;
cout<<"between 0 and 100 to the text file \"PrimeNumberList\"."<<endl<<endl;
cout<<"Find the list by using the file explorer to search for \"PrimeNumberList.txt\"."<<endl;
ofstream outFile;
outFile.open("PrimeNumberList.txt");
if (outFile.fail())
{
cout<<"Error opening \"PrimeNumberList.txt\" for output."<<endl;
return 1;
}
for (int i=1;i<100;i++)
{
if(isPrime(i))
{
outFile<<i<<endl;
}
}
return 0;
}
bool isPrime(int num1)
{
if (num1==1)return false;
bool primeNum=true;
for (int i=2;i<num1;i++)
{
if (num1%i==0)
{
primeNum=false;
}
}
return primeNum;
}