Allocate
 
Allocates a block of memory from the free store

Syntax

Declare Function Allocate cdecl ( ByVal count As Integer ) As Any Ptr

Usage

result = Allocate( count )

Parameters

count
The size, in bytes, of the block of memory to allocate.

Return Value

If successful, the address of the start of the allocated memory is returned. Otherwise, if the requested block size could not be allocated, or if count < 0, then the null pointer (0) is returned.

Description

Attempts to allocate, or reserve, count number of bytes from the free store (heap). The initial value of newly allocated memory is unspecified. The pointer that is returned is an Any Ptr and points to the start of the allocated memory. This pointer is guaranteed to be unique, even if count is zero.

Allocated memory must be deallocated, or returned back to the free store, with Deallocate when no longer needed.

Example

'' This program uses the ALLOCATE(...) function to create a buffer of 15 integers that is
'' then filled with the first 15 numbers of the Fibonacci Sequence, then output to the
'' screen. Note the call to DEALLOCATE(...) at the end of the program.

    Const integerCount As Integer = 15

    '' Try allocating memory for a number of integers.
    ''
    Dim buffer As Integer Ptr
    buffer = Allocate(integerCount * SizeOf(Integer))

    If (0 = buffer) Then
        Print "Error: unable to allocate memory, quitting."
        End -1
    End If

    '' Prime and fill the memory with the fibonacci sequence.
    ''
    buffer[0] = 0
    buffer[1] = 1
    For i As Integer = 2 To integerCount - 1
        buffer[i] = buffer[i - 1] + buffer[i - 2]
    Next

    '' Display the sequence.
    ''
    For i As Integer = 0 To integerCount - 1
        Print buffer[i] ;
    Next

    Deallocate(buffer)
    End 0

Output is:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
 

It is important to free allocated memory if it's not going to be used anymore. Unused memory that isn't freed is simply wasting memory, and if the address of that memory is somehow overwritten or forgotten, that memory can never be freed. This condition is known as a memory leak, and should be avoided at all costs. Note that leaked memory is always completely freed when the application terminates, either by an "ordinary" exit or crash, so the leak "persists" only as long as the application runs, nevertheless it's a good habit to free any allocated memory inside your application. The following example demonstrates a function with a memory leak, where the address of allocated memory is lost and isn't and can't be freed anymore. If such a function is called frequently, the total amount of memory wasted can add up quickly.

'' Bad example of Allocate usage, causing memory leaks

Sub BadAllocateExample()

    Dim p As Byte Ptr

    p = Allocate(420)   '' assign pointer to new memory

    p = Allocate(420)   '' reassign same pointer to different memory,
                        '' old address is lost and that memory is leaked

    Deallocate(p)

End Sub

    '' Main
    BadAllocateExample() '' Creates a memory leak 
    Print "Memory leak!"
    BadAllocateExample() '' ... and another
    Print "Memory leak!"
    End


Platform Differences

  • This procedure is not guaranteed to be thread-safe.

Dialect Differences

  • Not available in the -lang qb dialect unless referenced with the alias __Allocate

Differences from QB

  • New to FreeBASIC

See also

Знаете ли Вы, что cогласно релятивистской мифологии "гравитационное линзирование - это физическое явление, связанное с отклонением лучей света в поле тяжести. Гравитационные линзы обясняют образование кратных изображений одного и того же астрономического объекта (квазаров, галактик), когда на луч зрения от источника к наблюдателю попадает другая галактика или скопление галактик (собственно линза). В некоторых изображениях происходит усиление яркости оригинального источника." (Релятивисты приводят примеры искажения изображений галактик в качестве подтверждения ОТО - воздействия гравитации на свет)
При этом они забывают, что поле действия эффекта ОТО - это малые углы вблизи поверхности звезд, где на самом деле этот эффект не наблюдается (затменные двойные). Разница в шкалах явлений реального искажения изображений галактик и мифического отклонения вблизи звезд - 1011 раз. Приведу аналогию. Можно говорить о воздействии поверхностного натяжения на форму капель, но нельзя серьезно говорить о силе поверхностного натяжения, как о причине океанских приливов.
Эфирная физика находит ответ на наблюдаемое явление искажения изображений галактик. Это результат нагрева эфира вблизи галактик, изменения его плотности и, следовательно, изменения скорости света на галактических расстояниях вследствие преломления света в эфире различной плотности. Подтверждением термической природы искажения изображений галактик является прямая связь этого искажения с радиоизлучением пространства, то есть эфира в этом месте, смещение спектра CMB (космическое микроволновое излучение) в данном направлении в высокочастотную область. Подробнее читайте в FAQ по эфирной физике.

НОВОСТИ ФОРУМА

Форум Рыцари теории эфира


Рыцари теории эфира
 10.11.2021 - 12:37: ПЕРСОНАЛИИ - Personalias -> WHO IS WHO - КТО ЕСТЬ КТО - Карим_Хайдаров.
10.11.2021 - 12:36: СОВЕСТЬ - Conscience -> РАСЧЕЛОВЕЧИВАНИЕ ЧЕЛОВЕКА. КОМУ ЭТО НАДО? - Карим_Хайдаров.
10.11.2021 - 12:36: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от д.м.н. Александра Алексеевича Редько - Карим_Хайдаров.
10.11.2021 - 12:35: ЭКОЛОГИЯ - Ecology -> Биологическая безопасность населения - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> Проблема государственного терроризма - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> ПРАВОСУДИЯ.НЕТ - Карим_Хайдаров.
10.11.2021 - 12:34: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вадима Глогера, США - Карим_Хайдаров.
10.11.2021 - 09:18: НОВЫЕ ТЕХНОЛОГИИ - New Technologies -> Волновая генетика Петра Гаряева, 5G-контроль и управление - Карим_Хайдаров.
10.11.2021 - 09:18: ЭКОЛОГИЯ - Ecology -> ЭКОЛОГИЯ ДЛЯ ВСЕХ - Карим_Хайдаров.
10.11.2021 - 09:16: ЭКОЛОГИЯ - Ecology -> ПРОБЛЕМЫ МЕДИЦИНЫ - Карим_Хайдаров.
10.11.2021 - 09:15: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Екатерины Коваленко - Карим_Хайдаров.
10.11.2021 - 09:13: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вильгельма Варкентина - Карим_Хайдаров.
Bourabai Research - Технологии XXI века Bourabai Research Institution