[SOLVED] Possible bug with Arrays and Pointer inside a Structure

Just starting out? Need help? Post your questions and find answers here.
User avatar
Mijikai
Addict
Addict
Posts: 1520
Joined: Sun Sep 11, 2016 2:17 pm

[SOLVED] Possible bug with Arrays and Pointer inside a Structure

Post by Mijikai »

If a structure is arranged like this, the pointer might corrupt arrays or lead to crashes!
Maybe there is a bug within the memory management of arrays?

Example:

Code: Select all

;PureBasic 6.12 LTS (x64)
;Linux (Debian 12)

EnableExplicit

Structure DAT
  v.l
EndStructure

Structure DUMMY
  *p.DAT[0];<- a pointer to something - should not influence the arrays (if .DAT[0] is removed it works fine)!
  Array a.l(0,0)
  Array b.l(0,0)
EndStructure

Procedure.i Main()
  Protected *d.DUMMY
  *d = AllocateStructure(DUMMY)
  
  *d\p = *d\a()
  Dim *d\a(10,10)
  Dim *d\b(10,10)
  *d\a(0,0) = 1
  *d\b(0,0) = 1
  
  Debug "ArraySize a: " + Str(ArraySize(*d\a(),1)) + " & " + Str(ArraySize(*d\a(),2))
  Debug "ArraySize b: " + Str(ArraySize(*d\b(),1)) + " & " + Str(ArraySize(*d\b(),2)) 
    
  *d\p = *d\b();<- if *p contains a pointer to the second array the first one will be corrupted!?
  Dim *d\b(12,12)
  *d\b(0,0) = 1
     
  Debug "ArraySize a: " + Str(ArraySize(*d\a(),1)) + " & " + Str(ArraySize(*d\a(),2));<- array corrupted!?
  Debug "ArraySize b: " + Str(ArraySize(*d\b(),1)) + " & " + Str(ArraySize(*d\b(),2)) 
  
  FreeStructure(*d)
  ProcedureReturn #Null
EndProcedure

End Main()
Last edited by Mijikai on Sat Oct 05, 2024 6:59 pm, edited 1 time in total.
User avatar
STARGÅTE
Addict
Addict
Posts: 2259
Joined: Thu Jan 10, 2008 1:30 pm
Location: Germany, Glienicke
Contact:

Re: Possible bug with Arrays and Pointer inside a Structure

Post by STARGÅTE »

The definition of

Code: Select all

 *p.DAT[0]
means, you define an static array with 0 fields. When you then write to *d\p, this is not defined.

You probably want to do:

Code: Select all

Structure DAT
  v.l[0]
EndStructure

Structure DUMMY
  *p.DAT ; A pointer to DAT
  Array a.l(0,0)
  Array b.l(0,0)
EndStructure
PB 6.01 ― Win 10, 21H2 ― Ryzen 9 3900X, 32 GB ― NVIDIA GeForce RTX 3080 ― Vivaldi 6.0 ― www.unionbytes.de
Lizard - Script language for symbolic calculations and moreTypeface - Sprite-based font include/module
User avatar
Mijikai
Addict
Addict
Posts: 1520
Joined: Sun Sep 11, 2016 2:17 pm

Re: Possible bug with Arrays and Pointer inside a Structure

Post by Mijikai »

@ STARGÅTE thanks for your reply, that explains it. :oops:
*p.DAT is indeed what i wanted to do :)
User avatar
idle
Always Here
Always Here
Posts: 6026
Joined: Fri Sep 21, 2007 5:52 am
Location: New Zealand

Re: [SOLVED] Possible bug with Arrays and Pointer inside a Structure

Post by idle »

there should really be a description of this under static arrays in the structures section of the help
Call it a type iterator or something.
Post Reply