filmov
tv
CODESYS - Memory allocation of arrays and function blocks with the NEW & DELETE operators.

Показать описание
- __NEW and __DELETE operators
- Allocating a standard data_type and allocating a user_defined_type
- Accessing the elements of the allocated array with ptrName[n] and ptrName += (SIZEOF(DATA_TYPE)*n). (n=0...elements -1)
- Use of __NEW and __DELETE in a FB
TIPS:
- When the allocation with __NEW was successful the ptr != 0 else ptr = 0
- When __DELETE was successful the ptr = 0 else ptr != 0
- Use ptrName[n] and do not dereference the ptr^.
- Never allocate the same pointer twice if you haven't released the previously allocated memory. (memory leak)
- Do not use __DELETE if you haven't allocated a memory.
- Do not use __DELETE if your ptr doesn't point to the start ADR of the allocated memory.
- Always release the allocated memory when you are done with it.
- Never call the __NEW and __DELETE operators in two tasks simultaneously.
- As normal, you should never write something to an element of the array that doesn't exist! Example _ptrName[10] := 'BOOM'; when we have an array from 0..9!
- With __DELETE we delete the pointer, but the heap can still have some values from the previous allocation, so you should initialize the new array after its __NEW creation!
- The pragma {attribute 'enable_dynamic_creation'} is needed for using the __NEW operator for function blocks.
Explanation:
- If we allocate memory more then once without deleting the previous allocated memory, we are losing its address. That means that this memory will stay for ever allocated and it can’t be released with the __DELETE operator any more. (Memory leak) I have allocated 3 times an array with 10 STRING elements. The first two times I was able to do it, because 20x81bytes STRINGS = 1620 bytes, but on the third time I have received ptr=0 because my max value on the heap = 2000. Always release the allocated memory before using __NEW for the same pointer!
CORRECTION:
- For the sort FB I have allocated 13 elements, not 10 :)
Комментарии