decoding the runtime error (SIGFPE) - c++

This is a problem on spoj.com (http://www.spoj.com/problems/PRIC/) .We have to check whether numbers of the sequence : ai=( a(i-1)+1234567890 ) mod 2^31 are prime or not, 1st number is 1.
My code is given below (Please try to ignore the clumsiness.) based on sieve of eratosthenes .
The PROBLEM : We have to print "prime(1) or not(0)" for sequence upto i=33,333,333 , My code works perfectly fine for i( c3 in the code) values upto 8000 or so and after that (e.g c3>19000 ) it starts giving The SIGFPE error . Now i googled about the error , it has something to do with division/ mod by 0. But why is it that code works for c3 values upto 9000 but not beyond that?

Depending on your compiler and development environment, you should read up on the concept of a Debugger. This answer has a guide to use gdb. If you are using Visual Studio, Code::Blocks or any other IDE, look up the debugging features. For instance how to set a breakpoint or step into/out of/over a function call for instance, watching or changing variables etc. (I'm mentioning these things to give you vital hints for Google search-words, wink wink nudge nudge).
EDIT:
Copy-pasted the code and saved it, compiled with gcc -g for debug symbols and -lm to link the math library, I ran it through gdb and it gave me this output:
Program received signal SIGFPE, Arithmetic exception.
0x0000000000400707 in sieve (prime=0x6626a0) at t.c:43
43 if (a%prime2[j]==0){
This tells you to look at line 43, at the if statement that uses a modulo operation. This seems to be the place you are doing the modulo zero.
Do note that line 43 in the document I got when I copy-pasted your code from Stackoverflow, may not be line 43 in your document.
EDIT2:
Hey my answer was unaccepted! - why was that :) ?

Related

Scilab compilation "cannot allocate this quantity of memory"

I am facing issues with memory allocation in Scilab after compiling.
I am compiling on a Red Hat on ppc64 (POWER8). Stack limits are already set to unlimited (ulimit -s unlimited). The ./configure script (with several options I am not showing here) runs successfully, but the make all fails and stops. When it stops, it is stuck at the Scilab command prompt with this message:
./bin/scilab-cli -ns -noatomsautoload -f modules/functions/scripts/buildmacros/buildmacros.sce
stacksize(5000000);
!--error 10001
stacksize: Cannot allocate memory.
%s: Cannot allocate this quantity of memory.
at line 27 of exec file called by :
exec('modules/functions/scripts/buildmacros/buildmacros.sce',-1)
-->
I have investigated a bit, and that error message seems to be called of course at line 00027 in buildmatros.sce, where the function stacksize(5000000) is called.
This function is defined in:
scilab-5.5.1/modules/core/sci_gateway/c/sci_stacksize.c
I found a version of the file at this page: http://doxygen.scilab.org/master_wg/d5/dfb/sci__stacksize_8c_source.html.
The condition that is FALSE and that triggers the message seems to me to show up at line 00295.
Inside that file, you see that error is displayed whenever the stacksize given as input is LARGER than what is returned by the method get_max_memory_for_scilab_stack() from the class:
scilab-5.5.1/modules/core/src/c/stackinfo.c
Again I found a version online at the following page:
http://doxygen.scilab.org/master_wg/dd/dfb/stackinfo_8h.html#afbd65a57df45bed9445a7393a4558395
The Method is declared from line 109.
It seems to invoke a variable called MAXLONG, which is however NEVER explicitly declared! As you see, it is declared several times (line 00019, 00035, 00043, 00050), but all lines are commented! [correction: the lines are NOT commented, it was my false understanding of # being a comment sign, but it's not]
So my guess is: MAXLONG is not declared, so the function does not return a value (or it returns 0) and therefore the error message is triggered because the stacksize given as input is higher than 0 or NULL or N/A.
My questions are then:
Why are all lines commented where MAXLONG is defined?
Where does MAXLONG originate from? Is it something passed from the kernel?
How can I solve the problem?
Thanks!
PS - I tried to uncomment the line in buildmacros, and it compiled and installed without issues. However, when I started scilab-cli, it displayed the same message again.
Edit after further investigation:
After further investigation, I found out that what I thought were the comments are indeed instructions for the compiler... but I kept those errors of mine, so that the answer to my question is understandable.
Here are my new points.
In Scilab I noticed that by giving an input stacksize out of bounds, the same method get_max_memory_for_scilab_stack() is invoked, to get the upper bound. The lower bound I've seen it's defined by default.
-->stacksize(1)
!--error 1504
stacksize: Out of bounds value. Not in [180000,268435454].
Also the stacksize used seems fine:
-->stacksize()
ans =
7999994. 332.
However, when trying to give such value an input inbetween, it fails.
-->stacksize(1)
!--error 1504
stacksize: Out of bounds value. Not in [180000,268435454].
It seems to invoke a variable called MAXLONG
It's not a variable, but a pre-processor macro.
Why are all lines commented where MAXLONG is defined?
You should ask that from the person who commented the lines. They're not commented in scilab-5.5.1 that's online.
Where does MAXLONG originate from? Is it something passed from the kernel?
It's defined in the file scilab-5.5.1/modules/core/src/c/stackinfo.c. It's defined to the same value as LONG_MAX which is defined by the standard c library (<limits.h> header). If the macro is not supplied by the standard library, then it's defined to some other, platform specific value.
How can I solve the problem?
If your problem originates from the lack of definition for MAXLONG, then you must define it. One way going about it is to uncomment the lines that define it. Or re-download the original sources since yours don't appear to match with the official ones.

How to properly debug a binary generated by `go test -c` using GDB?

The go test command has support for the -c flag, described as follows:
-c Compile the test binary to pkg.test but do not run it.
(Where pkg is the last element of the package's import path.)
As far as I understand, generating a binary like this is the way to run it interactively using GDB. However, since the test binary is created by combining the source and test files temporarily in some /tmp/ directory, this is what happens when I run list in gdb:
Loading Go Runtime support.
(gdb) list
42 github.com/<username>/<project>/_test/_testmain.go: No such file or directory.
This means I cannot happily inspect the Go source code in GDB like I'm used to. I know it is possible to force the temporary directory to stay by passing the -work flag to the go test command, but then it is still a huge hassle since the binary is not created in that directory and such. I was wondering if anyone found a clean solution to this problem.
Go 1.5 has been released, and there is still no officially sanctioned Go debugger. I haven't had much success using GDB for effectively debugging Go programs or test binaries. However, I have had success using Delve, a non-official debugger that is still undergoing development: https://github.com/derekparker/delve
To run your test code in the debugger, simply install delve:
go get -u github.com/derekparker/delve/cmd/dlv
... and then start the tests in the debugger from within your workspace:
dlv test
From the debugger prompt, you can single-step, set breakpoints, etc.
Give it a whirl!
Unfortunately, this appears to be a known issue that's not going to be fixed. See this discussion:
https://groups.google.com/forum/#!topic/golang-nuts/nIA09gp3eNU
I've seen two solutions to this problem.
1) create a .gdbinit file with a set substitute-path command to
redirect gdb to the actual location of the source. This file could be
generated by the go tool but you'd risk overwriting someone's custom
.gdbinit file and would tie the go tool to gdb which seems like a bad
idea.
2) Replace the source file paths in the executable (which are pointing
to /tmp/...) with the location they reside on disk. This is
straightforward if the real path is shorter then the /tmp/... path.
This would likely require additional support from the compiler /
linker to make this solution more generic.
It spawned this issue on the Go Google Code issue tracker, to which the decision ended up being:
https://code.google.com/p/go/issues/detail?id=2881
This is annoying, but it is the least of many annoying possibilities.
As a rule, the go tool should not be scribbling in the source
directories, which might not even be writable, and it shouldn't be
leaving files elsewhere after it exits. There is next to nothing
interesting in _testmain.go. People testing with gdb can break on
testing.Main instead.
Russ
Status: Unfortunate
So, in short, it sucks, and while you can work around it and GDB a test executable, the development team is unlikely to make it as easy as it could be for you.
I'm still new to the golang game but for what it's worth basic debugging seems to work.
The list command you're trying to work can be used so long as you're already at a breakpoint somewhere in your code. For example:
(gdb) b aws.go:54
Breakpoint 1 at 0x61841: file /Users/mat/gocode/src/github.com/stellar/deliverator/aws/aws.go, line 54.
(gdb) r
Starting program: /Users/mat/gocode/src/github.com/stellar/deliverator/aws/aws.test
[snip: some arnings about BinaryCache]
Breakpoint 1, github.com/stellar/deliverator/aws.imageIsNewer (latest=0xc2081fe2d0, ami=0xc2081fe3c0, ~r2=false)
at /Users/mat/gocode/src/github.com/stellar/deliverator/aws/aws.go:54
54 layout := "2006-01-02T15:04:05.000Z"
(gdb) list
49 func imageIsNewer(latest *ec2.Image, ami *ec2.Image) bool {
50 if latest == nil {
51 return true
52 }
53
54 layout := "2006-01-02T15:04:05.000Z"
55
56 amiCreationTime, amiErr := time.Parse(layout, *ami.CreationDate)
57 if amiErr != nil {
58 panic(amiErr)
This is just after running the following in the aws subdir of my project:
go test -c
gdb aws.test
As an additional caveat, it does seem very selective about where breakpoints can be placed. Seems like it has to be an expression but that conclusion is only via experimentation.
If you're willing to use tools besides GDB, check out godebug. To use it, first install with:
go get github.com/mailgun/godebug
Next, insert a breakpoint somewhere by adding the following statement to your code:
_ = "breakpoint"
Now run your tests with the godebug test command.
godebug test
It supports many of the parameters from the go test command.
-test.bench string
regular expression per path component to select benchmarks to run
-test.benchmem
print memory allocations for benchmarks
-test.benchtime duration
approximate run time for each benchmark (default 1s)
-test.blockprofile string
write a goroutine blocking profile to the named file after execution
-test.blockprofilerate int
if >= 0, calls runtime.SetBlockProfileRate() (default 1)
-test.count n
run tests and benchmarks n times (default 1)
-test.coverprofile string
write a coverage profile to the named file after execution
-test.cpu string
comma-separated list of number of CPUs to use for each test
-test.cpuprofile string
write a cpu profile to the named file during execution
-test.memprofile string
write a memory profile to the named file after execution
-test.memprofilerate int
if >=0, sets runtime.MemProfileRate
-test.outputdir string
directory in which to write profiles
-test.parallel int
maximum test parallelism (default 4)
-test.run string
regular expression to select tests and examples to run
-test.short
run smaller test suite to save time
-test.timeout duration
if positive, sets an aggregate time limit for all tests
-test.trace string
write an execution trace to the named file after execution
-test.v
verbose: print additional output

delegatin assertion

Hi I want to improve my math library,
when I compute lenght of something I do
assert( !equal(len,0.0));
const f32 invsqrt = 1.0/sqrt(len);
X*= invsqrt;
Y*= invsqrt;
Z*= invsqrt;
this code is nice and if I do wrongly the division by zero the code breaks
"Runtime has requested to break application at line .. Vector.h line 88"
This is nice, but I want to do better, I want to show where error is REALLY.
So instead of showing "vector.h" and line 88 I want to show "main.cpp" "line 15" (if the getLength function is called at line 15 in main).
Vector is header only, so I think that achieving that is possible (that's just a feeling).. but how?
Thanks in advance. I hope you can see how usefull would be doing that.
That's where the code is, so that where it will break.
I think what you mean is to see the call stack.
In visual studio it's at: Debug -> Windows -> Call Stack.
The call stack can show you how you got to that line of code (which function were called in the work flow)

Why does using system("some.exe") in C++ method not work like the command line?

I am writing a program for Windows that eventually has to launch a different pre-existing .exe that sits on the same computer. It passes multiple parameters to this .exe file. I am reading the actual command and parameters and constructing the command but I also tried hard coding it with the same results. Here's the hard coded version (I picked this out of an older C program that uses the same.exe):
system("c://IQapture//dmon2_6_IHD -p2 c://IQapture//mon_table_101_Tx8.txt 11 0 0");
So in the original program inside int _cdecl main(int argc, char**argv) this use of system works. In my C++ program inside a C++ class method when I issue the command the correct program launches but it immediately puts up an error dialog stating that an error has occurred. I echo'd the system string used to launch the exe out to the console. Right after it fails, I copy and paste the same line that was echo'd and this time the exe runs without error. This is repeatable. In case it was timing related I tried adding a 10 second delay before issuing the system command but it didn't matter. Plus the original older program doesn't require a delay. This implies to me that the string is correct and the target program works. Somehow the system() invocation is different from a direct command line invocation. The program compiles and builds fine. I'm using Visual Studio 2010.
Does anyone have ideas on how to make the system() invocation work like the command line invocation?
That really doesn't look like the kind of thing that Windows would be happy with... Try it with backslashes instead:
system("c:\\IQapture\\dmon2_6_IHD -p2 c:\\IQapture\\mon_table_101_Tx8.txt 11 0 0");
If that still doesn't work, you quite likely have one of the following issues:
Your current working directory is wrong;
An environment variable is missing;
Your program is running with the wrong user permissions;
Your program is tying up a resource that the spawned process requires (eg you have not closed a file that it requires as input).
There are a lot of things to consider - the environment, the user running the program, the parent process and what's inherited... Take a look at the parameters to the CreateProcess function. Chances are your system call's invocation isn't matching the command line's (though that may not be the issue, simpler things are more likely.)
I'd advise working backwards from the error to rule out simple causes such as the environment, current directory, etc. before delving into such things as creation flags and security attributes.
You have your slashes backwards. Try:
system("c:/IQapture/dmon2_6_IHD -p2 c:/IQapture/mon_table_101_Tx8.txt 11 0 0");
You can use the backslash \ but because that is an escape sequence starter in a string (for C/C++) that is why you use two in a row. As the compiler will convert \\ into a single slahs in the string:
Thus:
system("c:\\IQapture\\dmon2_6_IHD -p2 c:\\IQapture\\mon_table_101_Tx8.txt 11 0 0");
// Is equivelent to the command line string:
> c:\IQapture\dmon2_6_IHD -p2 c:\IQapture\mon_table_101_Tx8.txt 11 0 0
But Windows has supported both types of slashes for longer than I can remember. So the following command line is equivalent.
> c:/IQapture/dmon2_6_IHD -p2 c:/IQapture/mon_table_101_Tx8.txt 11 0 0
Using '/' in a string (in C/C++) does not require escaping. So you just need to use it as is:
system("c:/IQapture/dmon2_6_IHD -p2 c:/IQapture/mon_table_101_Tx8.txt 11 0 0");

problem using formatted Fortran `write(6,*)` output

I'm currently porting an application from Fortran to C and need to output some variables to compare results. I'm very new to Fortran, and although i understand the code and have now ported several thousand lines, I'm a noob at writing Fortran code myself.
This code:
write(6,'(A,I3,A,E12.8,A,E12.8,A,E12.8,A,E12.8,A,E12.8)') 'iHyd:',
& ih,'; dzdr: ',dzdr,'; tauray:', tauRay,'; zRay: ',
& zray,'; ampRay: ',realpart(aray),'+j*',
& imagpart(aray),'; qRay: ',qray,'; width :',w
Compiles fine, but when run, the program exits with:
At line 296 of file calcpr.for (unit = 6, file = 'stdout')
Fortran runtime error: Expected INTEGER for item 15 in formatted transfer, got REAL
(A,I3,A,E12.8,A,E12.8,A,E12.8,A,E12.8,A,E12.8)
^
q0: 1432.3944878270595
nArrayR: 501 nArrayZ: 201
iHyd: 1; dzdr: ************; tauray:************; zRay: ************; ampRay: NaN+j* NaN
; qRay:
Besides being really ugly, it doesn't make much sense to me, as ìh is declared as integer*8 and not as real.
So how can i solve this?
I'm counting 6 character&variable specifications in the format statement, but you're printing 8 of them.
edit:
a nicer use of the format statement would be '(A,I3,7(A,E12.8))'
Fortran "recycles" the format if there are more things to be printed than specified in the format statement. If a write statement gives results you don't understand, to diagonose the problem it may be helpful to remove the things printed one at a time until the error goes away.
It says "item 15", which I would take to be down near the end of your list, not ih at the beginning. It's clear that both "w" and "qray" are being printed as REAL; is either one of them an INTEGER? You may need to change the format specifier then.