1
votes

In pascal programming language i wrote the following code

Program practice;
    //**** Function to get back N characters from a P position from a given string

  Function get_char(s1:String;n,p :Integer): String;
 Var
temp : String;
i : Integer;
Begin
temp:= s1[p];
 For i:= p+1 To p+n-1 Do
    temp := temp + s1[i];
get_char := temp;
End;
//**** end of the function *****
Var
  s1,s2: String;
  n,p: Integer;
Begin
    Write('Enter the number of char:');
    readln(n);
    write('Enter the position:' );
    readln(p);
    write('Enter the string : ');
    readln(s1);
    write(get_char(s1,n,p));
Readkey;
End.

Know that this function gets back a certain number of characters given by the user from a certain postion in the string . for example 'hello' with p = 1 and n =2 the result will be 'he' . Now imagine p is 3 and n =4 then then the output of the function will be 'lloA'. So my question is what happends in this case or why do we get such a result ? ( please give me details if its related to memory).

1
@TomBrunberg has given you a more general answer, but a specific glaring problem with your code is that temp:= s1[p] does not account for the case where s1 is empty. - MartynA
Your function is basically imitating the 'copy' function although the value of 'n' is different. You should check that p + n - 1 is not greater than length (s1), in which case a 'while' loop would be better than a 'for' loop. This would also detect the case where length (s1) = 0, as indicated by MartynA. - No'am Newman

1 Answers

4
votes

When your function reads characters beyond the end of the string, it reads memory content that happens to be in those memory positions, and interpretes that memory content as characters. Memory content beyond the length of a string is not defined, nor predictable. Some compilers add an explicit Char(0) as a terminating character. This zero character is not included in the length of the string.

To prevent wrong return values form your function, you can either,

  • a) turn range checking on in compiler settings, which will raise runtime errors

  • b) check that p + n - 1 <= Length(s) and if not, limit reading to Length(s).

Selecting option b gives a freedom to read until the end of any string by passing MaxInt for argument p.