Runtime Error encountered while running on Online Judges - c++

I have been solving this problem on SPOJ . One of the most frequent problems encountered while using online judges is Runtime Error. You never know which case leads to a Segmentation fault. Please help me figure out why does the code below correspond to a Runtime Error or Segmentation Fault even though I have ensured that every possible case runs properly on my linux gcc.
#include <iostream>
#include <math.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
int main ()
{
int t,i;
cin >> t;
string s;
vector<int> A;
while(t--)
{
cin >> s;
int n=s.size();
int temp;
if (n!=1)
{
for(i=0;i<s.size();i++)
{
A.push_back(s.at(i)-'0');
}
if(n%2!=0)
{ i = (n-1)/2;
while(A[i-1]==A[n-i])
i--;
i--;
}
else
{ i=n/2-1;
while(A[i]==A[n-1-i])
i-- ;
}
if (A[i]<A[n-i-1])
{
if ((n%2)!=0)
{
A[n/2] = A[n/2] + 1;
A[n-i-1] = A[i];
}
else
{
A[n/2-1] = A[n/2-1]+1;
A[n/2] = A[n/2-1];
A[n-i-1] = A[i];
}
}
else
A[n-i-1] = A[i];
while(i--)
A[n-i-1] = A[i];
while(!(A.empty()))
{
printf("%d",A.back());
A.pop_back();
}
}
else
cout << s;
}
}

I found one of your problems for segmentation fault , when you give for example "aaaaa" input to s you will get segmentation fault on this part of code
if(n%2!=0)
{ i = (n-1)/2;
while(A[i-1]==A[n-i])
i--;
i--;
}
because you didn't check i < 0 or not

Related

Why am I getting SIGCONT error on codechef ide?

I am getting SIGCONT error while running the code in codechef ide whereas on my local ide the same code runs fine.
The problem code is "TYPING" and it is from Snackdown Practice Contest: Beginner.
The code is below:
#include <iostream>
#include <iterator>
#include <map>
#include <string>
typedef long long ll;
ll FindCount(const char* str,ll num){
char previous =str[0];
ll individual_count=2;
for(ll i =1 ;i<num;i++){
if(previous=='d'||previous=='f'){
if(str[i]=='d'||str[i]=='f'){
individual_count+=4;
}
else{
individual_count+=2;
}
}
else{
if(str[i]=='j'||str[i]=='k'){
individual_count+=4;
}
else{
individual_count+=2;
}
}
previous=str[i];
}
return individual_count;
}
int main()
{
ll t;
std::cin>>t;
while(t--)
{
std::map<std::string,ll> m;
ll count=0;
ll n=0;
std::cin>>n;
while(n--){
std::string str;
std::cin>>str;
std::map<std::string,ll>::iterator itr;
itr=m.find(str);
if(itr!=m.end()){
count+=(itr->second)/2;
}
else{
ll num = str.size();
ll temp = FindCount(str.c_str(),num);
count+=temp;
m.insert({str,temp});
}
}
std::cout<<count<<"\n";
}
return 0;
}
The link to the problem statement is: https://www.codechef.com/SDPCB21/problems/TYPING
I am getting an infinite number of '0' as output each on new line.
Please tell me if there is any logical error or error of any kind in the code.
Thankyou.

Segmentation Fault Passing Reference as Function Parameter

With this block of code, I'm getting a segmentation fault as I try to pass the stack references to the transferStacks() method. Any help on understanding why this is would be helpful!
I could just get rid of the helper method and it should work, but I'm trying to understand conceptually.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
void transferStacks(stack<int> & s1, stack<int> & s2){
if (s1.empty()){
for (int i = 0; i < s2.size(); i++){
int element = s2.top();
s1.push(element);
s2.pop();
}
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int queries = 0;
cin>>queries;
stack <int> newestOnTop;
stack <int> oldestOnTop;
while (queries!=0){
int type = 0;
cin >> type;
int input = 0;
if (type == 1){ //enqueue
cin>>input;
newestOnTop.push(input);
}
else if (type == 2){ //dequeue
transferStacks(newestOnTop, oldestOnTop);
oldestOnTop.pop();
}
else if (type == 3){ //peek
transferStacks(newestOnTop, oldestOnTop);
cout<<oldestOnTop.top()<<endl;
}
queries--;
}
return 0;
}
Segmentation Fault
You appear to believe that this code will copy s2 to s1:
for (int i = 0; i < s2.size(); i++){
int element = s2.top();
s1.push(element);
s2.pop();
}
But it will not: if before the loop s2 contains 3 elements, only the first 2 will be copied (and generally, only the first half will be copied).
In addition, your transfer function transfers from s2 to s1, but the way you call it implies that you intended the opposite: to transfer from s1 to s2. Current code would leave oldestOnTop empty, which will then result in a crash when you use oldestOnTop.top() or oldestOnTop.pop().

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.

Code Crashes Immediately After Running

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?