[Solved] String callocate/reallocate fails with FB64

New to FreeBASIC? Post your questions here.
Post Reply
noop
Posts: 130
Joined: Sep 18, 2006 10:29

[Solved] String callocate/reallocate fails with FB64

Post by noop »

Hi,

I don't see why the following doesn't work (FB 64-bit on 64-bit Win7 using "-w pedantic -exx -g"):

Code: Select all

dim as string ptr x = callocate(1,sizeof(string))
if x <> 0 then
    x[0] = "a"
    for i as integer = 2 to 10
        x = reallocate(x,i*sizeof(string))
        if x <> 0 then x[i-1] = "b"
    next i
end if
It crashes with the error
c0000374
Something stack related. Seems to work fine with FB-32-bit.
Last edited by noop on Mar 15, 2016 10:00, edited 1 time in total.
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: String callocate/reallocate fails with FB64

Post by fxm »

There is a bug in the code.
That works with fbc 32-bit by chance.

When the memory is reallocated, the added memory zone is not cleared (at opposite of Callocate).
So the added string descriptor is not cleared and the instruction 'x[i-1]' begins to try to deallocate the previous string (because the descriptor is not cleared) => possible crash.

Before use the new allocated string, one must clear its descriptor:

Code: Select all

dim as string ptr x = callocate(1,sizeof(string))
if x <> 0 then
    x[0] = "a"
    for i as integer = 2 to 10
        x = reallocate(x,i*sizeof(string))
        if x <> 0 then
            clear x[i-1], 0, sizeof(string)
            x[i-1] = "b"
        end if
    next i
end if
noop
Posts: 130
Joined: Sep 18, 2006 10:29

Re: String callocate/reallocate fails with FB64

Post by noop »

Thanks fxm!
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: [Solved] String callocate/reallocate fails with FB64

Post by fxm »

About this mistake, there is already a note in documentation at page KeyPgReallocate:
.....
When manually allocating memory for String descriptors (or UDTs that contain one), if count is larger than the original size of the memory block, the new extra memory range must be explicitly cleared to zeroes before the first string use (for example, using Clear). Otherwise accessing the string will cause undefined results (trying to write or read at a random place in memory, or trying to deallocate a random pointer).
.....
Post Reply