# Dynamic Memory Allocation in SQL

> When executing SQL queries a "runtime" object is created. This runtime includes its own allocator method that is used for all memory allocation in the context of this query. When the query finishes, all memory allocated by this allocator is released automatically.

> The allocator object is a member of the runtime and can be accessed inside the UDF:. For example (for a typical C++ UDF):

>         McoSql::Value* gen_quotes(McoSql::Runtime *runtime, McoSql::Vector<McoSql::Value>* args)
>         {
>             McoSql::Allocator allocator = runtime->allocator;
>             ...
>         }

> Note that this function receives a pointer to the runtime object and the vector of parameters `args`. It is expected that the function returns a Value created with the runtime's allocator as well. For example:

>         return McoSql::IntValue::create(runtime->allocator, nquotes);

> The function arguments are allocated prior to the function call and will be destroyed after the function has returned. If some of the function's arguments are needed to be used at a later time by the application, (for example stored in some other object), the corresponding vector element could be assigned NULL. For example:

>         args->items[0] = NULL;

> It is also possible to create an allocator inside the UDF. For example:

>         McoSql::Value* gen_quotes(McoSql::Runtime *runtime, McoSql::Vector<McoSql::Value>* args)
>         {
>             McoSql::Allocator temp_allocator;
>             ...
>             McoValue *temp_int = McoSql::IntValue::create(runtime->allocator, nquotes);
>             ...
>             // No need to destroy temp_int, it will be destroyed automatically
>         }