[fpc-pascal] Function to create a record ?

Jean SUZINEAU jean.suzineau at wanadoo.fr
Mon Jun 5 11:56:59 CEST 2023


Hello, I have a hard time trying to understand what you want to test.

In your functions, you are using a record, not a class or a pointer to 
record or an object.

The personrecord just behave in your parameters and return value as an 
Integer or a String, and your fillchar doesn't write outside of the 
memory allocated for you junkvar, so I don't see what can go wrong.

If you trace the address of person.name like this:

//begin code
begin
	person := newperson();
         writeln('1, person.name address: ', IntToHex(Int64(Pointer(@(person.name)))));
	fillchar(junkvar, junkvar_size, 'a');
	person2 := newperson();
	fillchar(junkvar, junkvar_size, 'b');
	person := modperson(person, 'Martin');
	person := modperson(person2, 'Maria');
         writeln('2, person.name address: ', IntToHex(Int64(Pointer(@(person.name)))));
	{writeln(junkvar);}
	writeperson(person);
	writeperson(person2);
end.
//end code

You'll see that the address doesn't change, for example:

1, person.name address: 000000000050C7F0
2, person.name address: 000000000050C7F0


But if you declare your personrecord as a class, the things doesn't 
behave the same way:

//begin code
const
	junkvar_size = 20000000;

type
	personclass = class
	name: string;
	end;
var
	person: personclass;
	person2: personclass;
	junkvar: array[1..junkvar_size] of char;

function newperson(): personclass;
var newp: personclass;
begin
      newp:= personclass.Create;
	newp.name := '';
	newperson := newp;
end;

function modperson(person: personclass; name: string): personclass;
begin
	person.name := name;
	modperson := person;
end;

procedure writeperson(person: personclass);
begin
	writeln(person.name);
end;

begin
	person := newperson();
         writeln('1, person.name address: ', IntToHex(Int64(Pointer(@(person.name)))));
	fillchar(junkvar, junkvar_size, 'a');
	person2 := newperson();
	fillchar(junkvar, junkvar_size, 'b');
	person := modperson(person, 'Martin');
	person := modperson(person2, 'Maria');
         writeln('2, person.name address: ', IntToHex(Int64(Pointer(@(person.name)))));
	{writeln(junkvar);}
	writeperson(person);
	writeperson(person2);
end.
//end code


You'll get a different address, something like:


1, person.name address: 00007FFFF7F910E8
2, person.name address: 00007FFFF7F91108
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20230605/37845855/attachment-0001.htm>


More information about the fpc-pascal mailing list