Segment violation (was Re: Why I could not cast string to int?)
bearophile
bearophileHUGS at lycos.com
Thu Feb 2 10:30:29 PST 2012
xancorreu:
> I get "segment violation" error with ./factorial 400000
> How can I resolve it?
You are having a stack overflow. DMD currently doesn't print a good message because of this regression that is being worked on:
http://d.puremagic.com/issues/show_bug.cgi?id=6088
On Windows with DMD you increase the stack like this:
dmd -L/STACK:100000000 -run test2.d 400000 > result.txt
If it goes in overflow still, increase the stack some more. But it will take a long time to compute the result even with the latest 2.058head with improved GC because the algorithm you have used to compute the factorial is very bad.
I have rewritten your code like this:
import std.stdio, std.bigint, std.conv, std.exception;
BigInt recFactorial(in int n) {
if (n == 0)
return BigInt(1);
else
return BigInt(n) * recFactorial(n - 1);
}
void main(string[] args) {
if (args.length != 2) {
writeln("Factorial requires a number.");
} else {
try {
writeln(recFactorial(to!int(args[1])));
} catch (ConvException e) {
writeln("Error");
}
}
}
Note the usage of ConvException, it's a very good practice to never use a generic "gotta catch them all" expression, because it leads to hiding other bugs in your code, and this is a source for troubles.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list