* * *

Author Topic: What exactly does string assignment do?  (Read 370 times)

Artlav

  • New member
  • *
  • Posts: 28
    • Orbital Designs
What exactly does string assignment do?
« on: August 24, 2017, 03:26:35 am »
I've been having weird problems with strings and threads.

Given a and b, both of which are "string" type (ansistring, to be precise), what does a:=b; actually do?
Does it allocate the space for a and copy b's content, or does it create a reference from a to b? Or something else?

See an example below.
The procedure is getting called from various threads, and the strings keep disappearing and losing the last character in them.

Both case A and case B give problems, but they differ a bit.

Code: Pascal  [Select]
  1. type dstkrec=record
  2.  c:boolean;
  3.  n,f:string;
  4. end;  
  5.  
  6. var dstack:array[0..DSTKS-1]of dstkrec;  
  7.  
  8. procedure add(const fn,dir:string);
  9. var i,c:integer;
  10. begin    
  11.  mutex_lock(ar_mx);
  12.   c:=-1;
  13.   for i:=0 to DSTKS-1 do if not dstack[i].c then begin c:=i; break; end;
  14.   if c<>-1 then begin
  15.    dstack[c].c:=true;
  16.  
  17. {$ifdef casea}
  18.    //Case A:
  19.    dstack[c].f:=fn;
  20.    dstack[c].n:=dir;
  21. {$else}
  22.    //Case B:
  23.    setlength(dstack[c].f,length(fn));
  24.    move(fn[1],dstack[c].f[1],length(fn));
  25.    setlength(dstack[c].n,length(dir));
  26.    move(dir[1],dstack[c].n[1],length(dir));
  27. {$endif}
  28.  
  29.   end;
  30.  mutex_release(ar_mx);
  31. end;
  32.  

molly

  • Hero Member
  • *****
  • Posts: 1813
Re: What exactly does string assignment do?
« Reply #1 on: August 24, 2017, 03:39:15 am »
Ansistrings are reference counted. More information can be read here.
Quote
Assigning one ansistring to another doesn’t involve moving the actual string. A statement    S2:=S1;

results in the reference count of S2 being decreased with 1, The reference count of S1 is increased by 1, and finally S1 (as a pointer) is copied to S2.

User137

  • Hero Member
  • *****
  • Posts: 1717
    • Nxpascal home
Re: What exactly does string assignment do?
« Reply #2 on: August 24, 2017, 08:55:29 pm »
What's best way to copy it into new string, this?

Code: Pascal  [Select]
  1. S2:=S1+'';

howardpc

  • Hero Member
  • *****
  • Posts: 2308
Re: What exactly does string assignment do?
« Reply #3 on: August 24, 2017, 10:17:53 pm »
Code: Pascal  [Select]
  1. s2:=s1;
  2. UniqueString(s2);

 

Recent

Get Lazarus at SourceForge.net. Fast, secure and Free Open Source software downloads Open Hub project report for Lazarus