Recent

Author Topic: Memory safety tips for designing excellent and terrible code  (Read 232 times)

cpicanco

  • Hero Member
  • *****
  • Posts: 618
  • Behavioral Scientist and Programmer
    • Portfolio
Memory safety tips for designing excellent and terrible code
« on: March 01, 2024, 01:12:01 pm »
The White House of the United States published some good news for the Pascal community:

Quote
Using a memory safe language can help prevent programmers from introducing certain
types of memory-related issues. Memory is managed automatically as part of the
computer language; it does not rely on the programmer adding code to implement
memory protections. The language institutes automatic protections using a combination
of compile time and runtime checks. These inherent language features protect the
programmer from introducing memory management mistakes unintentionally. Examples
of memory safe language include Python®, Java®, C#, Go, Delphi/Object Pascal, Swift®,
Ruby™, Rust®, and Ada.

Object Pascal is mentioned before Rust, which is really nice. A thread is discussing the news here:

https://forum.lazarus.freepascal.org/index.php/topic,66428.0.html

So, how about taking advantage of this hype to leave your recommendations ‘off the top of your head’ for writing both secure and terribly insecure code?

Here are my (naive) memory safety tips to Self := Me:

- learn the difference about stack and heap memory;
- learn how to use the heaptrc unit to track heap memory leaks;
- When doing class inheritance, as a rule of thumb, avoid "constructor Create; reintroduce" (I really don't have any concrete example where reintroduce would be really necessary), use "constructor Create; override" or "constructor Create;" for virtual and for normal methods, respectively;
- When doing inheritance from TObject:

Code: Pascal  [Select][+][-]
  1. TMyClass = class
  2.   constructor Create;
  3.   destructor Destroy; override;
  4. end;
  5.  

Always start your constructor with:

Code: Pascal  [Select][+][-]
  1. constructor TMyClass.Create;
  2. begin;
  3.   inherited Create;
  4.  
  5. end;
  6.  

- use the constructor to initialize variables and memory only and use the destructor to free stuff, do not use them to jump through hoops;
- I don't have tips for CORBA interfaces (I am still learning about them).
Be mindful and excellent with each other.
https://github.com/cpicanco/

 

TinyPortal © 2005-2018