Allocated memory is always 8 bytes

New to FreeBASIC? Post your questions here.
bdc90
Posts: 1
Joined: Mar 12, 2021 20:03

Allocated memory is always 8 bytes

Postby bdc90 » Mar 12, 2021 20:22

Hi, I spend my free time learning programming in FreeBASIC. However, I'm having some trouble with the Allocate and Callocate functions. No matter what value I enter into the size/count parameters, it only allocates 8 bytes of memory. For example, this code should get stuck in an infinite loop:

Code: Select all

Dim As UByte Ptr bArray

Do
   bArray = Callocate(3,1) 'Allocate 3 bytes
Loop Until Len(bArray) = 8   'Exit loop if 8 bytes allocated

For i As ULong = 0 To Len(bArray)-1 Step 1
   bArray[i] = i + 3
   Print bArray[i]
Next

DeAllocate(bArray)

Sleep


But it doesn't. I have no idea what could be causing this. Is this a bug? Am I doing something wrong? Does anyone else have this problem?
MrSwiss
Posts: 3826
Joined: Jun 02, 2013 9:27
Location: Switzerland

Re: Allocated memory is always 8 bytes

Postby MrSwiss » Mar 12, 2021 20:48

Hi,

I'm just assuming here, what you seem to want to do:

Code: Select all

Dim As Ubyte        uba(0 To 15)        ' ubyte array (16 elements)
Dim As UByte Ptr    puba = @uba(0)      ' pointer to array

For i As ULong = 0 To UBound(uba)
   puba[i] = i + 3
   Print puba[i]
Next

Sleep
For this implementation there isn't any memory fiddling necessary (C/Allocate & DeAllocate).
badidea
Posts: 2333
Joined: May 24, 2007 22:10
Location: The Netherlands

Re: Allocated memory is always 8 bytes

Postby badidea » Mar 12, 2021 23:05

bdc90 wrote:Hi, I spend my free time learning programming in FreeBASIC. However, I'm having some trouble with the Allocate and Callocate functions. No matter what value I enter into the size/count parameters, it only allocates 8 bytes of memory. For example, this code should get stuck in an infinite loop:

Code: Select all

Dim As UByte Ptr bArray

Do
   bArray = Callocate(3,1) 'Allocate 3 bytes
Loop Until Len(bArray) = 8   'Exit loop if 8 bytes allocated

For i As ULong = 0 To Len(bArray)-1 Step 1
   bArray[i] = i + 3
   Print bArray[i]
Next

DeAllocate(bArray)

Sleep


But it doesn't. I have no idea what could be causing this. Is this a bug? Am I doing something wrong? Does anyone else have this problem?

There are several things going wrong in that code.
A) Len(bArray) does (unfortunately) not return the size of the array. In returns the size in bytes of a pointer (4 for 32-bit fbc, 8 for 64-bit fbc).
B) Do : bArray = Callocate(3,1) : Loop Until Len(bArray) = 8 is how you create a memory leak. You ask the computer 3 bytes of memory each time, but on next loop you overwrite the pointer that points to the memory and the location of the previous 3 bytes is lost.

You can increase the size of an allocated memory block with Reallocate. But it is unclear to me what you actually want to do.

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 4 guests