Segment violation (was Re: Why I could not cast string to int?)

Timon Gehr timon.gehr at gmx.ch
Thu Feb 2 13:55:06 PST 2012


On 02/02/2012 08:04 PM, xancorreu wrote:
> Al 02/02/12 19:30, En/na bearophile ha escrit:
>> 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
> Thank you very much for recode this. But you "only" put a "in" in
> recFactorial function argument. What this mean? **Why** this is more
> efficient than mine?

It is not. He just added some stylistic changes that don't change the 
code's semantics in any way.

>
> For the other hand, how can increase the stack in linux?
>
>
> Thanks,
> Xan.

I don't know, but it is best to just rewrite the code so that it does 
not use recursion.

(This kind of problem is exactly the reason why any language standard 
should mandate tail call optimization.)



More information about the Digitalmars-d-learn mailing list