[fpc-pascal] Pointer
Jonas Maebe
jonas.maebe at elis.ugent.be
Wed Nov 16 11:01:14 CET 2005
On 15 nov 2005, at 17:11, Luis Del Aguila wrote:
> Somebody can help me.
> I do not understand, that I am making bad.
> The program is:
>
> Program ProbandoMemoria;
> {$R+}
> Var
> PLPunteros: ^Pointer;
> NuevoTamanio : integer;
> elementos : longint;
> x,b : ^integer;
> Begin
> elementos := 3;
> NuevoTamanio:=Sizeof(Pointer)*elementos;
> ReallocMem(PlPunteros,NuevoTamanio);
> Writeln('Direccion : ',longint(Plpunteros) );
> new(x);
> x^:=7;
> Plpunteros^:=x;
> b:=Plpunteros^;
> Writeln('Direccion : ',longint(b),' valor : ',b^);
> new(x);
> x^:=15;
> (Plpunteros+4)^:=x;
In this statement (and several next ones) you are writing past the
memory allocated for Plpunteros. Adding a value to a pointer,
increases the value of said pointer by this value times the size of
the elements the pointer points to. Since Plpunteros = ^Pointer, the
above writes X to the address "pointer(plpunteros)+4*sizeof(pointer)".
What you want is "(Plpunteros+1)^:=x;". Or, if you are in fpc or
objfpc mode, you can also use "plpunteros[1]:=x;"
> b:=(Plpunteros+4)^;
> Writeln('Direccion : ',longint(b),' valor : ',b^);
> new(x);
> x^:=25;
> (Plpunteros+8)^:=x;
> b:=(Plpunteros+8)^;
> Writeln('Direccion : ',longint(b),' valor : ',b^);
>
> //This I do not understand.
> //Why ' b^ ' does not have the 7?
Probably because one of the previous out-of-bounds writes overwrote
the value.
Jonas
More information about the fpc-pascal
mailing list