Page 1 of 1

Structures "on-the-fly"

Posted: Mon Nov 13, 2006 10:17 am
by jqn
Hi,
I dont know if this subject subject has been treated before. But if it serves for somebody:

Code: Select all

Structure mystruc
  mylong.l
  mystring.s
...
Endstructure


  *struc.mystruc  = Allocatememory(sizeof(mystruc))
  *struc\mylong   = sizeof(mystruc)
  *struc\mystring = "Loaded dato on the string..."
  ...

; At end you need to de-allocate string data
  *struc\mystring = ""
  Freememory(*struc)

It runs for my, but only few tests.

JOAQUIN

Posted: Mon Nov 13, 2006 8:45 pm
by Xombie
Be careful here as I've run into a major problem with this in the past - using memory allocated structures and strings. See...

http://www.purebasic.fr/english/viewtopic.php?t=23099

... this posting for a solution from freak. Unless this behavior has changed in 4.01 beta for Windows and is now fixed.

Posted: Mon Nov 13, 2006 9:01 pm
by Trond
jqn's code will leak memory like a waterfall.

Posted: Mon Nov 13, 2006 10:08 pm
by Xombie
I guess I should've added this originally to show the more correct method...

Code: Select all

Structure mystruc 
  mylong.l 
  mystring.s 
EndStructure 
;-
Procedure FreePBString(*Address) 
   ; Procedure and method of removing structure strings from memory from freak @ http://www.purebasic.fr/english/viewtopic.php?t=23099&start=0
   Protected String.String
   ; The String Structure contains one String element, which is initialized to 0 on procedure start 
   PokeL(@String, *Address)
   ; poke our strings address into the structure.  When returning, PB's string free routine for the local structure will actually free the passed string.
EndProcedure
;-
*struc.mystruc  = AllocateMemory(SizeOf(mystruc)) 
*struc\mylong   = SizeOf(mystruc) 
*struc\mystring = "Loaded dato on the string..." 
; At end you need to de-allocate string data 
FreePBString(@*struc\mystring)
;
FreeMemory(*struc) : *struc = 0
;-
End
;-

Posted: Mon Nov 13, 2006 10:48 pm
by Konne
Will FreeMemory work if I copy the String with CopyMemory and just save the Pointer as Pointer in the Structure?
I mean, it should...