dynamic arrays and the lack of them in C

I love Pascal and Delphi. In particular I love its memory management.
I can use string, array of byte types. They are both dynamic arrays. They are not just pointers to a memory region, they have a size or Length (how Delphi calls them).
The great thing about them is that they can be re-sized. But an other great thing is that you can check their sizes no matter what (if you forgot to remember them, or if you receive them as argument of a function/procedure/method).
SetLength()
Length()
Low()
High()
Open array parameters
^^^^ This is what I need in C!

In C it’s like they want to hide this information from you. First, there is no such thing as dynamic array in C (there are only pointers). There are arrays in C++ (but I read that you should avoid them at all cost, and use vector instead), but also you cannot re-size them, so they are not fixed length, but not really dynamic either.
So how can you get the length of an array or memory region?
common methods:
In C you can use #define lengthof(array) (sizeof(array)/sizeof(array[0])) if it’s a fixed length array, but you cannot use it on function arguments, or pointers…

There is a clever template (if you write it) in C++
template
inline unsigned int length( T(&a)[N] ) { return N; }
that can be used to determine length of arrays.

So where are the real dynamic, realizable arrays, and how to implement them?
If you want to allocate memory run-time (and re-size them) you can use malloc() (realloc() and free())
That’s all fine until you want to get the size of them. Which can happen if you allocate the memory outside of a function where you want to use it. There is no std libc function to get the (malloc) allocated memory size which is kept somewhere (so free() can free it, realloc can re-size it and available memory regions can be kept track of). There is however a GNU extension malloc_usable_size() which I, we desperately need (even if we didn’t know it).
.. Well we need an array whose size we can check no matter if it’s dynamic or static, but…
Also note that malloc_usable_size does NOT actually return the requested size, but the allocated one (due to alignment, minimum block size), but at least we can use it for asserts.
So we still need to keep track of array sizes separately (extra variables, extra arguments) and risk messing them up…
(or rewrite everything to use structures of size, pointer pairs)

Another topic is multidimensional (dynamic) arrays (not just arrays of arrays)…

Note: This actually I have written just now 🙂 See I do not just reuse ages old materials:)

Hungarian notation

Hungarian notation is usually miss-interpreted as the notation of declared type of variable. This is not the case. So when I read a book that says that Hungarian notation is useless in type safe languages, I feel bad. 🙁

Hungarian notation is supposed to indicate semantic type (type of content, meaning) and not syntactical type (type of variable). The compiler knows how to handle (read, write, do operations with) variables, but it has no idea what they are, what they mean. And if you are not naming your variables right you might not either.

Lets say you are writing some physics calculation. You are probably do not want to add mass with length or acceleration… (you might want to multiply, divide them but not add, subtract). To the compiler (even the most type safe ones) they are all just floating point numbers (or doubles, extendeds). And if you are naming your variables like marias_speed, peter_is_this_fast, velocity_of_kevin, then you are looking for trouble. It’s harder to notice the error in this: marias_speed + peter_is_this_fast + mass_of_kevin, than in this: veMaria + vePeter + maKevin. In this case Hungarian notation could mean units of measurement.
The same goes if you are calculating screen position in pixels, inches, centimeters…

The more common task a programmer has to deal with is user input. User input is always unsafe! An SQL string is (or should be) treated differently than user input, or html text… strings need to be escaped differently for different output. So it might be advantageous to include in the variable name if it’s unsafe, html-safe, sql-safe …
Also use printf(“%s”,usStr) rather than printf(usStr) 🙂

Note: I found this old draft from 2012 January. Another one again… I shouldn’t misplace these 🙂

Why Delphi / pascal is better than C++

Ok, there are characteristics where c++ has the advantage, but I’m not talking about that now.

Delphi has properties! They are great if you are in the process of creating a new library. Why? Because when you start you can just set a bunch of variables public, you do not need to implement setter and getter functions. Later you can decide to make some of those variables private, and create properties and setter functions for them (checking, limiting range, do stuff on change). Usually you do not need to write getter functions at all.

private
FPosStart,FPosEnd:integer; /// ...
protected
procedure SetPosStart(value:integer); /// ...
published
property PosStart:integer read FPosStart write SetPosStart;

The main advantage here is not that we do not have to write getter function.
Imagine that the library is used extensively (by you, or others). AFAIK in C++ a change like this would break compatibility. Code would have to be changed to PosStart() / getPosStart() and setPosStart(…) form ‘… PosStart’ and ‘PosStart = …’

In Delphi constructors are inherited. It’s not a big deal, I did not even realize it until now. I’m reading Large Scale C++ Software Design about cyclic dependencies, levelization, mutually dependant components. It suggests not to write constructors that convert between classes, but rather write separate converter class with static methodes. But that does not seem very objectum oriented to me. It reminds me of itoa() and stuff like that. It works but still… So, I was wondering why not create descendant classes (or ancestor classes) and implement an additional constructor in the descendant class, that converts form the ancestor classes. It’s a little more typing but not much… or so I thought, then I realized that I needed to reimplement all the ancestors constructors… which is not the case in delphi. It’s a rather common practice to use your own descendant classes of standard controls from the start, just in case you will ever need to add some functionality. It’s easy, and cheap.
TMyCollection = class(TCollection) end;

Digitális Technika 1 HF 1

Csináltam a Digitális Technika 1 kereszt féléves 1. házi ellenörzéséhez, javításához egy weboldalt. Kis Huffman kódolás, számábrázolás, Hamming távolság, paritás számítás. A Karnaugh tábla ellenörzésére idő hiányában már nem született automatizált meoldás.

Legtöbbször amikor php-ban írok valamit szinte mindig elÅ‘fordul valamilyen adatbázis kezelés, mint például a Mérés Labor Jelentkezés oldal készítésénél is. Most eddig itt még nem kellett ehhez. Persze lehetne a bemeneti adatokat valahonnan importálni, vagy az eredményeket exportálni, adatbázisban rögzíteni. Esetleg késÅ‘bb a hallgatók adhatnák le megoldásaikat webes felületen…

Were is Waldo … I mean my mouse

It can be annoying to find your mouse pointer, especially on multiple monitors. So I wrote a little tool in Delphi that moves the cursor to the center of the monitor. It’s really easy:

  Mouse.CursorPos := Point(
    Screen.Monitors[0].Left+Screen.Monitors[0].Width div 2,
    Screen.Monitors[0].Top+Screen.Monitors[0].Height div 2
  );

A couple of other lines like RegisterHotkey and a Tray Icon and it’s done.

MO

 

https is not so safe

Wireshark provides a cool feature: decrypt ssl (https) traffic. But how is that possible? Isn’t https supposed to be private, unbreakable, provide protection against 3rd parties listening in?
Yes, and it does… most of the time. In order to decrypt the data, you need the server’s private key. Which you don’t have usually, but others might get their hands on. And this is the problem.
If someone logs your traffic (maybe for years), and later acquires the private keys, then they can decrypt all your data sent over ssl.
This can be done only if the key exchange is RSA, because this uses the server’s “constant” private key to encrypt the session key.
If https uses Diffie–Hellman key exchange, then every session key is generated and exchanged securely. Meaning the key is generated from and encrypted with random data, and not stored anywhere. This key exchange method was designed to exchange keys over insecure, public channels. So it is not possible for 3rd party to get the key, and the information used to generate and exchange the keys are temporary, and destroyed on both sides after the key exchange is over.

Diffie–Hellman key exchange is part of many Chipper Suit, but unfortunately many sites (like google, facebook) does not include, support this. As if they do not really want for you to have complete privacy…
https channel can only be established if both sides support (at least one) same chipper.

To see and edit what chippers your Firefox browser supports open ‘about:config‘, and search for ‘ssl’.

Related Articles:
http://www.netresec.com/?page=Blog&month=2011-01&post=Facebook-SSL-and-Network-Forensics

USB Mouse Raw Data

A Fujitsu-Siemens Wireless egeremhez nincs 64 bites windows driver. Az alap dolgok persze e nélkül is mennek, de van rajta néhány gomb, amit az OS nem ismer fel.

Probáltam libusb-win32-vel kinyerni az adatokat, ami csak többé kevésbé volt sikeres. A filter funkciót használtam.
Egyik egérnél csak a forgalom egy részét kapta el, elég sok csomag elkerülte. A Fujitsu-Siemens egérnél ugyan elkapott minden csomagot, de ezzel együtt le is választotta az op-rendszerről (a mutató mozgásra és kattintásra nem reagált).

Az egyik fórumon olvastam a GetRawInputData Win API függvényt. Eltartott egy ideig, de sikerült beüzemelni, viszont ez meg csak azokat az adatokat továbbítja, amit a windows egyébként is kezel.

Nem valószínű hogy most nekiállok windows drivert írni az egeremhez, de lehet hogy majd egyszer…

Tray Timer

Összeraktam egy kis időzítő programot ma. Ez nem ébresztő óra, arra ott van az outlook, lightning (thunderbird), vagy akár a google online naptára. (Meg még vagy ezer maásik program).
Ez arra jó, ha gyorsan be akarjuk állítani, hogy pl. 10 perc mulva jelezzen (hogy megfőtt a kemény tojás).
Gyorsan és egyszerűen egérrel, vagy billentyűzettel be tudjuk állítani, lehet hang jelzéssel, vagy a nélkül, egyszerre akár több (korlátlan) időzítőt is elindíthatunk, lehet utána törölni a feleslegeseket.

Még kicsit félkész, de már jól használható.

FSTrayTimer_bin_20110201
FSTrayTimer_src_20110201