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

preview_player
Показать описание

- __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 :)
Рекомендации по теме
Комментарии
Автор

good job. The video is a good introduction to __NEW and __DELETE with all its pitfalls. Great!

stefanhenneken
Автор

Very cool, thank you! Looks like Codesys 3.5 ST is a full-blown OOP language, so flexible. Inheritance, encapsulation, polymorphism, it supports all of those. Sweet

Denial
Автор

Your videos are of great help to me, thanks again!

meganivanova
Автор

very good, if you could host it somewhere it would be very good, to be able to have the example projects ...
Thanks for everything.

Runtimevic
Автор

Goog explanation. But the amount of ads throughout the video is beyond funny.

Shabazza
Автор

Can i use memory allocation by __NEW for interfaces?

tolegator