Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2019-06

TStringList/pchar question

3 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Ryan Joseph

I just learned that pchar is not ref counted like I used to think so I’m curious why this code doesn’t fail. Shouldn’t this crash because I free TStringList and then access GetText?

strings := TStringList.Create;
strings.LoadFromFile(vertexShaderPath);
vertexShaderSource := strings.GetText;
strings.Free;
glShaderSource(vertexShaderID, 1, @vertexShaderSource, nil);

Regards,
Ryan Joseph

Michael Van Canneyt
to Ryan Joseph
Ryan Joseph wrote
I just learned that pchar is not ref counted like I used to think so I’m curious why this code doesn’t fail. Shouldn’t this crash because I free TStringList and then access GetText?

You're first doing gettext and then freeing. So this is OK.

Show quoted text 6 lines
strings := TStringList.Create; strings.LoadFromFile(vertexShaderPath); vertexShaderSource := strings.GetText; strings.Free; glShaderSource(vertexShaderID, 1, @vertexShaderSource, nil);

You'll get a memory leak, unless you're freeing vertexShaderSource further on.

See also
https://www.freepascal.org/docs-html/rtl/classes/tstrings.gettext.html

Michael.

Ryan Joseph
to Michael Van Canneyt
Show quoted text 5 lines
On Jun 2, 2019, at 2:48 PM, Michael Van Canneyt wrote: > I just learned that pchar is not ref counted like I used to think so I’m curious why this code doesn’t fail. Shouldn’t this crash because I free TStringList and then access GetText? You're first doing gettext and then freeing. So this is OK.

I thought pchar was ref counted so by calling GetText I was retaining ownership but GetText is allocating a new string (https://www.freepascal.org/docs-html/rtl/classes/tstrings.gettext.html). Sorry I didn’t read the documentation because I made a bad assumption about ref counting. Thanks.

Regards,
Ryan Joseph