Announcement

Collapse
No announcement yet.

Dynamic Memory Allocation

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Dynamic Memory Allocation

    I have a little problem,

    I cannot fugure out how to write variables to the heap and
    keep them static, dynamically.

    I will not know at design time how many I will need but need
    to create them to order. In C++ i believe it is done with
    the keyword 'new' and in 'C' a similar thing can be accomplished
    with 'malloc'

    What is the PB equivalent, or technique needed to do this.

    The example is writing a linked list in memory. Written by
    one function, read by another etc. By keeping the root node
    global I always know where to find it but new items are added
    as needed and because they are added to the list I only need to
    set up a pointer in the previous node.

    The problem is that the function that wrote the item to the list
    deallocates the variable as the function exits, and I cannot declare
    any more than the root node as global because I will not know
    how many items there are going to be.

    Any help greatly appreciated.

    Trevor


    ------------------

  • #2
    CoTaskMemAlloc / CoTaskMemFree ?!
    Code:
        #Register None
        #Dim All
        Declare Function CoTaskMemAlloc Lib "ole32.dll" Alias "CoTaskMemAlloc" (ByVal Dword) As Dword
        Declare Sub CoTaskMemFree Lib "ole32.dll" Alias "CoTaskMemFree" (ByVal Dword)
    
        Type MyInfo
           PtrToNext As Dword
           Info As String * 1000000
        End Type
        %n = 20
        Function PbMain
           Local i As Long, PtrToRoot As Dword, PtrToEl As Dword
           Dim pMyInfo As MyInfo Ptr
           Print "See Memory (before CoTaskMemAlloc) in Task Manager": WaitKey$
           For i = 1 To %n
              PtrToEl = CoTaskMemAlloc(Len(MyInfo))
              If PtrToRoot = 0 Then PtrToRoot = PtrToEl Else _
                 @pMyInfo.PtrToNext = PtrToEl
              pMyInfo = PtrToEl
              @pMyInfo.PtrToNext = 0: @pMyInfo.Info = "Line" + Str$(i)
           Next
           Print "See Memory (after CoTaskMemAlloc) in Task Manager": WaitKey$
           PtrToEl = PtrToRoot
           For i = 1 To %n
              pMyInfo = PtrToEl
              Print Left$(@pMyInfo.Info, 50)
              PtrToEl = @pMyInfo.PtrToNext
              CoTaskMemFree pMyInfo
           Next
           Print "See Memory (After CoTaskMemFree) in Task Manager": WaitKey$
           
        End Function
    ------------------
    E-MAIL: [email protected]

    [This message has been edited by Semen Matusovski (edited October 02, 2000).]

    Comment


    • #3
      Semen,

      Many thanks.

      Trevor

      ------------------

      Comment

      Working...
      X