Portál AbcLinuxu, 1. prosince 2025 17:53
malloc(), alokuje se o trochu větší blok, na začátek se zapíše jakási hlavička (u glibc AFAIK 8 byte) a pointer, který dostanete, ukazuje až za ni. Funkce free() pak odečte délku té hlavičky a tam najde vše potřebné. Proto je tak riskantní volat free() na pointer, který nebyl získán pomocí malloc() (nebo jeho sourozenců).
Podobný problém v C++ (uložení počtu objektů při alokování pole) se popisuje v The C++ FAQ:
Short answer: Magic.
Long answer: The run-time system stores the number of objects, n, somewhere where it can be retrieved if you only know the pointer, p. There are two popular techniques that do this. Both these techniques are in use by commercial-grade compilers, both have tradeoffs, and neither is perfect. These techniques are:
* Over-allocate the array and put n just to the left of the first Fred object.
* Use an associative array with p as the key and n as the value
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.