19.0.0 released Nov 08, 2023
New mem

Purpose: Allocate memory.

new-mem [ define ] <memory> size <size> \
    [ block-size <block size> ] \
    [ init ]

new-mem allocates <memory> of <size> blocks, each block of <block size> bytes as specified in "block-size" clause, thus allocating <size>*<block size> bytes aligned suitably for any pointer type. By default, block size is 1, which means in that case <size> is the number of bytes. <memory> is allocated memory.

When "init" is used, the memory is zero-initialized. If you need the memory initialized, always use "init" as it is generally faster than creating memory and then initializing it (for instance with "memset()").

If "define" is used, variable <memory> is created if it does not exist. The pointer returned is always "void*" and can be used for any purpose; always cast it to your desired type.

If an existing pointer is used (i.e. without "define"), then such pointer can be of any type.
Examples
Allocate memory of 300 bytes, producing a "void *". Then the data is copied into it - note the casting to "char*";
new-mem define mystr size 300
strcpy ((char*)mystr, "Some string");

Initialize memory of 1000 bytes (filled with all zeroes):
new-mem define mymem size 1000 init

Allocate an array of 1000 integers:
int *mymem;
new-mem mymem size 1000 block-size sizeof(int)

Allocate an array of 1000 integers initialized to 0 and then a single element of the array is assigned a value:
int *mymem;
new-mem mymem size 1000 block-size sizeof(int) init
mymem[50] = 23;

The memory can be created as "void *" and then assigned to any type:
new-mem define mymem size 1000 block-size sizeof(int) init
int *newmem = (int*)mymem;

See also
Memory
delete-mem  
manage-memory  
memory-handling  
new-mem  
resize-mem    
See all
documentation


You are free to copy, redistribute and adapt this web page (even commercially), as long as you give credit and provide a dofollow link back to this page - see full license at CC-BY-4.0. Copyright (c) 2019-2023 Dasoftver LLC. Vely and elephant logo are trademarks of Dasoftver LLC. The software and information on this web site are provided "AS IS" and without any warranties or guarantees of any kind. Icons from table-icons.io copyright Paweł Kuna, licensed under MIT license.