Version française
Home     About     Download     Resources     Contact us    
Browse thread
small code problem
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: <Brad Knotwell <knotwell@f...>
Subject: small code problem

Hello all--

I'm having a problem with a core dump due to an uncaught exception.
The following snippet of code best illustrates the problem:

let usage = lazy (Printf.printf "Usage: %s file\n" Sys.argv.(0); exit ~-1);;
let filename =
        try
           Sys.argv.(1)
        with Invalid_argument("Array.get") ->
           Lazy.force usage;;

When I compile using the byte-code compiler, it seems to work fine.

         [knotwell@knotwell stock]$ ocamlc junk.ml
	 [knotwell@knotwell stock]$ ./a.out
	 Usage: ./a.out file
	 [knotwell@knotwell stock]$ 

On the other hand, when I compile with the optimizing compiler, I
receive the following:

	[knotwell@knotwell stock]$ ocamlopt junk.ml
	[knotwell@knotwell stock]$ ./a.out
	Segmentation fault (core dumped)
        [knotwell@knotwell stock]$	
When I change the code slightly:


let usage = lazy (Printf.printf "Usage: %s file\n" Sys.argv.(0); exit ~-1);;
let filename =
        try
           Sys.argv.(1)
        with _ ->          (* note the pattern matching change *)
           Lazy.force usage;;

I then get correct results:

       [knotwell@knotwell stock]$ ocamlopt junk.ml
       [knotwell@knotwell stock]$ a.out
       Usage: a.out file
       [knotwell@knotwell stock]$	

Why do the two compilers exhibit different behaviors with the same code?

As an aside, I don't particular like my use of lazy and force.  Is
there a cleaner way do the same thing?

Thanks.

--Brad