"Segment fault" error :-(_(re)

Thu, 9 Oct 1997 00:32:54 +0200 (MEST)


According to Christian Bockermann:
> chris@bockermann:/home/chris/programs/pascal/indent > a.out
> Segmentation fault

This means that you have written to some memory where you were not allowed
to write to.  In this case it means that you have filled the string beyond
its capacity.  Let's see why:

> 	program test;
> 
> 	type tstr = string[30];
> 
> 	var s_test : tstr;
> 
> 	function copy (s : tstr; p1 : integer; p2 : integer ) : tstr;

(* Here you can save some typing by writing "p1, p2: Integer". *)

> 	var
> 	   i   : integer;
> 	   buf : tstr;
> 	begin
> 	   for i:=p1 to p2 do

What you mean is: "for i:= p1 to p2 + p1 do".

> 	      buf[i]:=s[i];
> 	   copy:=buf;

Here is the problem:  You have assigned some characters to the string,
but not a length.  Now, "copy:= buf" assigns a string of *random* length
to the variable `buf' with a capacity of 30 which causes the crash.

> 	end;
> 	
> 	begin
> 	   s_test:='Dies ist ein Test-string';
> 	   writeln(copy(s_test,5,4));
> 	end.

To solve the problem you can either directly assign a length to the string
- which is currently only possible by using some more-or-less dirty tricks -
or you do it this way:

    buf:= '';
    for i:= p1 to p1 + p2 do
      buf:= buf + s [ i ];
    copy:= buf;

BTW (= by the way), your procedure does not check whether `p1 + p2' or even
`p1' is in the range of the string `S'.

> (By the way, if you have suggestions for a better style of programming
> this copy-function, please let me know, I'm already learning ... :-)

You mean:  You are *still* learning. :-)

No problem with this - your style is very good.  I have seen a much worse
programming style from people who consider themselves "computer freaks".
(I may say it here because noone of them is on this list (hopefully).;-)

Good luck,

    Peter

 Dipl.-Phys. Peter Gerwinski, Essen, Germany, free physicist and programmer
peter.gerwinski@uni-essen.de - http://home.pages.de/~peter.gerwinski/ [971005]
 maintainer GNU Pascal [971001] - http://home.pages.de/~gnu-pascal/ [971005]


Peter Gerwinski (peter@agnes.dida.physik.uni-essen.de)

HTML conversion by Lluís de Yzaguirre i Maura
Institut de Lingüística Aplicada - Universitat "Pompeu Fabra"
e-mail: de_yza@upf.es