an error occur when running a c++ script in cygwin - c++

I tryed to run the following code in my cygwin
#include<iostream>
#include<cstdio>
using namespace std;
const int NR=2005;
int n,m;
bool arr[NR][NR];
int mx_jx(int x){
int up[NR][NR],lf[NR][NR],rt[NR][NR];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
up[i][j]=1,lf[i][j]=rt[i][j]=j;
for(int i=1;i<=n;i++)
for(int j=2;j<=m;j++)
if(arr[i][j-1]==x)lf[i][j]=lf[i][j-1];
for(int i=1;i<=n;i++)
for(int j=m-1;j>=1;j--)
if(arr[i][j+1]==x)rt[i][j]=rt[i][j+1];
int ans=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
if(arr[i][j]!=x)continue;
if(i>1 && arr[i-1][j]==x){
up[i][j]=arr[i][j-1]+1;
lf[i][j]=max(lf[i][j],lf[i-1][j]);
rt[i][j]=min(rt[i][j],rt[i-1][j]);
}
ans=max(ans,(rt[i][j]-lf[i][j]+1)*up[i][j]);
}
return ans;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
int tmp;
scanf("%d",&tmp);
arr[i][j]=(int)tmp;
if((i+j)&1)arr[i][j]=!arr[i][j];
}
printf("%d",max(mx_jx(0),mx_jx(1)));
return 0;
}
It passed the compile(0 warning,0 error), but when I tried to run it with the following input
4 4
0 1 1 1
1 1 1 0
0 1 1 0
1 1 0 1
It says "Command terminated"
these code could run correctly on other platform, how can I solve this problem on cygwin? thanks a lot

While the answer from user3684240 is valid and it is definitely an issue with your code, more likely you have Stack Overflow due to allocating numerous huge arrays on stack and in global memory area.
You should use std::vector<std::vector<int> instead of plain C arrays.
std::vector<std::vector<int>> up(NR, std::vector<int>(NR, 0));
std::vector<std::vector<int>> lf(NR, std::vector<int>(NR, 0));
std::vector<std::vector<int>> rt(NR, std::vector<int>(NR, 0));
It is not very well optimized, but it's simplest solution I can provide.
For that bool array though, std::vector might behave... strange. I cannot give 100% guarantee that it will work if you simply substitute bool[][] with std::vector<std::vector<bool>> without testing it properly, because std::vector<bool> is optimized for memory and it has certain quirks that one should be aware of when using it.
You can try and see if that array of bools in global memory works (after changing arrays in mx_jx to vectors), maybe it does and you don't have to change it. If it doesn't, you can try to change to vector of vectors, then it should work.

The mistake is in that line:
scanf("%d", &arr[i][j]);
%d reads ints, but your array is of type bool. This leads to a memory error.
An easy way to fix it would be:
int read_value;
scanf("%d", &read_value);
arr[i][j] = read_value;
As an additional hint: If you enable compiler warnings (-Wall -Wextra -pedantic), the compiler will tell you about those kinds of mistakes.

Related

Recursive code exits with exit code 3221225477

I am new to c++ programming and StackOverflow, but I have some experience with core Java. I wanted to participate in programming Olympiads and I choose c++ because c++ codes are generally faster than that of an equivalent Java code.
I was solving some problems involving recursion and DP at zonal level and I came across this question called Sequence game
But unfortunately my code doesn't seem to work. It exits with exit code 3221225477, but I can't make anything out of it. I remember Java did a much better job of pointing out my mistakes, but here in c++ I don't have a clue of what's happening. Here's the code btw,
#include <iostream>
#include <fstream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
int N, minimum, maximum;
set <unsigned int> result;
vector <unsigned int> integers;
bool status = true;
void score(unsigned int b, unsigned int step)
{
if(step < N)
{
unsigned int subtracted;
unsigned int added = b + integers[step];
bool add_gate = (added <= maximum);
bool subtract_gate = (b <= integers[step]);
if (subtract_gate)
subtracted = b - integers[step];
subtract_gate = subtract_gate && (subtracted >= minimum);
if(add_gate && subtract_gate)
{
result.insert(added);
result.insert(subtracted);
score(added, step++);
score(subtracted, step++);
}
else if(!(add_gate) && !(subtract_gate))
{
status = false;
return;
}
else if(add_gate)
{
result.insert(added);
score(added, step++);
}
else if(subtract_gate)
{
result.insert(subtracted);
score(subtracted, step++);
}
}
else return;
}
int main()
{
ios_base::sync_with_stdio(false);
ifstream input("input.txt"); // attach to input file
streambuf *cinbuf = cin.rdbuf(); // save old cin buffer
cin.rdbuf(input.rdbuf()); // redirect cin to input.txt
ofstream output("output.txt"); // attach to output file
streambuf *coutbuf = cout.rdbuf(); // save old cout buffer
cout.rdbuf(output.rdbuf()); // redirect cout to output.txt
unsigned int b;
cin>>N>>b>>minimum>>maximum;
for(unsigned int i = 0; i < N; ++i)
cin>>integers[i];
score(b, 0);
set<unsigned int>::iterator iter = result.begin();
if(status)
cout<<*iter<<endl;
else
cout<<-1<<endl;
cin.rdbuf(cinbuf);
cout.rdbuf(coutbuf);
return 0;
}
(Note: I intentionally did not use typedef).
I compiled this code with mingw-w64 in a windows machine and here is the Output:
[Finished in 19.8s with exit code 3221225477] ...
Although I have an intel i5-8600, it took so much time to compile, much of the time was taken by the antivirus to scan my exe file, and even sometimes it keeps on compiling for long without any intervention from the anti-virus.
(Note: I did not use command line, instead I used used sublime text to compile it).
I even tried tdm-gcc, and again some other peculiar exit code came up. I even tried to run it on a Ubuntu machine, but unfortunately it couldn't find the output file. When I ran it on a Codechef Online IDE, even though it did not run properly, but the error message was less scarier than that of mingw's.
It said that there was a run-time error and "SIGSEGV" was displayed as an error code. Codechef states that
A SIGSEGV is an error(signal) caused by an invalid memory reference or
a segmentation fault. You are probably trying to access an array
element out of bounds or trying to use too much memory. Some of the
other causes of a segmentation fault are : Using uninitialized
pointers, dereference of NULL pointers, accessing memory that the
program doesn’t own.
It's been a few days that I am trying to solve this, and I am really frustrated by now. First when i started solving this problem I used c arrays, then changed to vectors and finally now to std::set, while hopping that it will solve the problem, but nothing worked. I tried a another dp problem, and again this was the case.
It would be great if someone help me figure out what's wrong in my code.
Thanks in advance.
3221225477 converted to hex is 0xC0000005, which stands for STATUS_ACCESS_VIOLATION, which means you tried to access (read, write or execute) invalid memory.
I remember Java did a much better job of pointing out my mistakes, but here in c++ I don't have a clue of what's happening.
When you run into your program crashing, you should run it under a debugger. Since you're running your code on Windows, I highly recommend Visual Studio 2017 Community Edition. If you ran your code under it, it would point exact line where the crash happens.
As for your crash itself, as PaulMcKenzie points out in the comment, you're indexing an empty vector, which makes std::cin write into out of bounds memory.
integers is a vector which is a dynamic contiguous array whose size is not known at compile time here. So when it is defined initially, it is empty. You need to insert into the vector. Change the following:
for(unsigned int i = 0; i < N; ++i)
cin>>integers[i];
to this:
int j;
for(unsigned int i = 0; i < N; ++i) {
cin>> j;
integers.push_back(j);
}
P.W's answer is correct, but an alternative to using push_back is to pre-allocate the vector after N is known. Then you can read from cin straight into the vector elements as before.
integers = vector<unsigned int>(N);
for (unsigned int i = 0; i < N; i++)
cin >> integers[i];
This method has the added advantage of only allocating memory for the vector once. The push_back method will reallocate if the underlying buffer fills up.

Segmentation fault(core dumped) c++

The following program gives the correct output but gives segmentation fault(core dumped in the end)
#include <iostream>
using namespace std;
int main()
{
int a[50],n,i,c[50],b[50];
cin>>n;
for(i=1;i<=n;i++)
cin>>a[i];
for(i=1;i<=100;i++)
b[i]=0;
for(i=1;i<=n;i++)
{
b[a[i]]++;
}
for(i=2;i<=100;i++)
{
b[i]=b[i]+b[i-1];
}
for(i=1;i<=n;i++)
{
c[b[a[i]]]=a[i];
b[a[i]]--;
}
for(i=1;i<=n;i++)
cout<<c[i]<<endl;
return 0;
}
Here is the debugger output
gdb
Apart from other conditions in your program, at least this loop causes a buffer overflow and hence invokes undefined behavior!
for(i=1;i<=100;i++)
b[i]=0;
That is, because b has only 50 elements, and you're accessing memory waaay beyond that range. Also C arrays a zero-index based.
Note, that you likely cause UB in other statements as well, but this one was the first I noticed skimming over your code.
You are going out of bounds here:
for(i=2;i<=100;i++)
{
b[i]=b[i]+b[i-1];
}
since b is an array of size 50 and you allow i to reach the value of 100 and index the array. This causes the segmentation fault.
PS: Other loops may also index your arrays out of bounds, depending on the input you receive, since you don't check the input.

C++:Linker command with exit code -1 in xcode

I was implementing a suffix array in xcode using c++ when I got the following error:
ld: 32-bit RIP relative reference out of range (100000121018926 max is +/-4GB): from _main (0x100001310) to _L (0x5AF417B0F130) in '_main' from /Users/priya/Library/Developer/Xcode/DerivedData/cfquestions-boqlvazrozappdeetfhesfsohczs/Build/Intermediates/cfquestions.build/Debug/cfquestions.build/Objects-normal/x86_64/main.o for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
My code for the suffix array is as follows:
char a[size1];
int ans[size2][size2];
struct node{
int gg[2],pos;
}L[size1];
int step=1,ct=1;
bool comp(node a, node b){
return a.gg[0]==b.gg[0]?(a.gg[1]<b.gg[1]?1:0):(a.gg[0]<b.gg[0]?1:0);
}
int main(){
int TT;
cin>>TT;
while(TT--){
set<int> s;
//a.clear();
int n=strlen(a);
scanf("%s",a);
for(int i=0;i<strlen(a);i++)ans[0][i]=a[i]-'a';
for(;ct<strlen(a);step++,ct<<=1){
for(int i=0;i<n;i++){
L[i].gg[0]=ans[step-1][i];
L[i].gg[1]=i+ct<n?ans[step-1][i+ct]:-1;
L[i].pos=i;
}
sort(L,L+n,comp);
for(int i=0;i<n;i++)
ans[step][L[i].pos]=i>0&&L[i].gg[0]==L[i-1].gg[0]&&L[i].gg[1]==L[i-1].gg[1]?ans[step][L[i-1].pos]:i;
}
for(int i=0;i<n;i++)
{
if(s.find(ans[step-1][i])!=s.end()){
}
else s.insert(ans[step-1][i]);
}
cout<<s.size()<<endl;
}
return 0;
}
P.S: The code runs fine on any other code. I tried even much more complex codes; but it works fine. Hence there must be something wrong with this piece of code- but I am not able to figure out what!
Any help would be appreciated thanks!!
edit: The reason is the size of ans, as pointed out in the comment by #WhozCraig after you added the sizes. My guess regarding why the linker error message names _L is that the compiler put main at a lower address and then the global data in order, giving the too big RIP offset to L.
In one of the for loops you have i = 0 and access L[i-1], which is a very large number for the array index .
edit: but that should give a runtime failure or error and not give a linker error.

trailing zeros in a factorial.when i run it on ideone.com i'm getting runtime error with infinite output. Even SPOJ is also not accepting

#include <iostream>
#include <cmath>
using namespace std;
int func(int n){
int count=0;
float t=log(n)*0.621;
int k=(int)t;
int temp;
for(int i=1;i<=k;i++){
int power=1;
for(int j=0;j<i;j++){
power=power*5;
}
temp=(int)(n/power);
count=count+temp;
}
return count;
}
int main(){
int t;
cin>>t;
for (int i=0;i<t;i++){
int n;
cin>>n;
cout<<func(n)<<'\n';
}
return 0;
}
I'm getting correct answer for few test cases.The error i'm getting in ideone is
Runtime error time: 0 memory: 3100 signal:25
33628713
33628713
33628713
33628713
33628713
33628713
with infinite output when no input is given
I don't know what the logarithm is doing in your code. You somehow use it to determine when to stop dividing by powers of 5. It appears to be an approximation, and if you only get correct answers sometimes, then I expect that the approximation's inaccuracy is working against you.
You don't need the logarithm. You could simply stop the loop when you determine that there are no more factors of powers of 5 remaining. Think about how you could detect that using the values you've already calculated.
You don't need to approximate anything. A page at Purplemath explains and demonstrates how to calculate the number of trailing zeroes in a factorial number. Read the article and see whether you can recognize how the technique described there corresponds to parts of your code, and also notice how there are no logarithms involved on that page.

C++/RAII: Could this cause a memory leak?

I have a weird problem. I have written some MEX/Matlab-functions using C++. On my computer everything works fine. However, using the institute's cluster, the code sometimes simply stops running without any error (a core file is created which says "CPU limit time exceeded"). Unfortunately, on the cluster I cannot really debug my code and I also cannot reproduce the error.
What I do know is, that the error only occurs for very large runs, i.e., when a lot of memory is required. My assumption is therefore that my code has some memoryleaks.
The only real part where I could think of is the following bit:
#include <vector>
using std::vector;
vector<int> createVec(int length) {
vector<int> out(length);
for(int i = 0; i < length; ++i)
out[i] = 2.0 + i; // the real vector is obviously filled different, but it's just simple computations
return out;
}
void someFunction() {
int numUser = 5;
int numStages = 3;
// do some stuff
for(int user = 0; user < numUser; ++user) {
vector< vector<int> > userData(numStages);
for(int stage = 0; stage < numStages; ++stage) {
userData[stage] = createVec(42);
// use the vector for some computations
}
}
}
My question now is: Could this bit produce memory leaks or is this save due to RAII (which I would think it is)? Question for the MATLAB-experts: Does this behave any different when run as a mex file?
Thanks