303 points · by goranmoomin · 4y ago · 163 comments
eg, from the 4.4 BSD, circa 1993:
https://minnie.tuhs.org/cgi-bin/utree.pl?file=4.4BSD/usr/src...
void *
calloc(num, size)
size_t num;
register size_t size;
{
register void *p;
size *= num;
if (p = malloc(size))
bzero(p, size);
return(p);
}[0] https://msrc-blog.microsoft.com/2021/04/29/badalloc-memory-a...
[1] Full list: https://www.cisa.gov/uscert/ics/advisories/icsa-21-119-04
[1]: https://github.com/rofl0r/musl/blob/d05aaedaabd4f5472c233dbb...
Makes me wonder what kind of compiler flags muslibc uses to prevent this.
> 7.24.3.2 The calloc function
> […]
> Returns
> The calloc function returns either a pointer to the allocated space or a null pointer if the space cannot be allocated or if the product nmemb * size would wraparound size_t.
Gah! "Wraparound" is not a verb! You'd think someone writing a computer language specification would try to use (human) language correctly.
Am I the only one that doesn’t think this is “sweet”?
I mean I know what it does and why and how it works, but IMHO a good language should let you express your intention and algorithm in human terms and logic in which there is no -1 value for an unsigned integer type.
I'd rewrite it as `if (n != 0 && m > SIZE_MAX / n)`. Seems legit to me.
With these functions, it could be written as: if (__builtin_mul_overflow(n, m, &n))
if (n && m > SIZE_MAX / n)Shouldn't the case of wraparound be caught by testing the resulting size as following?
s = n*m;
if (n && s >= n && s >= m) /* no overflow */ ...----
The first version of UNIX to include `calloc` was Research UNIX V6, and here's how it was implemented: https://github.com/dspinellis/unix-history-repo/blob/Researc...
calloc(n, s)
{
return(alloc(n*s));
}
There are several interesting things we learn from poking around V6:- `calloc` originated not on UNIX, but as part of Mike Lesk's "iolib", which was written to make it easier to write C programs portable across PDP 11 UNIX, Honeywell 6000 GCOS, and IBM 370 OS[0]. Presumably the reason calloc is the-way-it-is is hidden in the history of the implementation for GCOS or IBM 370 OS, not UNIX. Unfortunately, I can't seem to track down a copy of Bell Labs "Computing Science Technical Report #31", which seems to be the appropriate reference.
- `calloc` predates `malloc`. As you can see in the above code, there was a `malloc`-like function called just `alloc` (though there were also several other functions named `alloc` that allocated things other than memory). (Ok, fine, since V5 the kernel's internal memory allocator happened to be named `malloc`, but it worked differently[1]).
[0]: https://github.com/dspinellis/unix-history-repo/blob/Researc... (format with `nroff -ms usr/doc/iolib/iolib`)
[1]: https://github.com/dspinellis/unix-history-repo/blob/Researc...
By that, I mean the title of this article, 'Why does calloc exist?'. My guess would be that back in the origins of the C library:
1) Few cared about automatic overflow checks, that was a job for the programmer, so it seems unlikely the creators added calloc() specifically so that it could check if m * n overflowed (after all, there are loads of libc calls that will shoot you in the foot if you don't do overflow/buffer size checks)
2) calloc() is ancient, probably pre-dating many virtual memory optimisations, and back then, memory was relatively fast vs instruction execution, so adding calloc() to speed up giant memory allocations would be less impactful. But that's just a hunch, and I'm often surprised by just how sophisticated early UNIX code was. Early computing was slow, every performance gain you could squeeze out of the system mattered and if there were VMs that could defer zeroing memory until it was really needed then people would probably try to do that.
But my guess is, calloc() was simply a helper function, added because it was very common to malloc() some memory and then zero it straight away. Does anyone know the actual history?
"Why is calloc useful?" would be probably a better title.
Apparently I was more correct than I realized.
In the specific case of Rust, no, because not all values are valid. E.g., in the case of Rust, bool must be true (literally 1) or false (0); other values are UB. &str data must be valid UTF-8. Violating these invariants can cause other code that might depend on them to do odd things. E.g., an Option<bool> might rely on one of the other 254 values for the None variant[1], a UTF-8 decoder knowing the data "is" valid UTF-8 need not bound check continuation bytes leading to accesses outside the butter.
> Why can't we wait and let that be the first value that's actually meaningful instead of wasting time writing 0's?
Well, in Rust, see MaybeUninit (https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.h...). The docs page goes into the UB a bit, too (and names the above examples). So, you can … but it's often easier to just write a 0 or a known value & let the compiler make sure it's safe and optimize it out if it can.
[1]: Example: https://play.rust-lang.org/?version=stable&mode=debug&editio... — Option<bool> is 1 byte because the Option can take advantage of bool only using 2 out of 256 values of its byte. Cf. https://frehberg.com/2022/01/rust-memory-layout-optimization... and the first link in that.
Also, many C programmers (in my experience) don't use calloc -- they just use malloc, and then they initialize the memory. The basic danger is that you forget to initialize part of it, and then you have garbage data in your object fields. Zeros are arbitrary, but at least they (usually) cause a seg fault if you try to dereference them as a pointer, for example.
I guess there's a secondary danger that even if you do initialize all the fields, you might end up with padding bits that don't get initialized, and those would contain parts of an earlier object. That shouldn't usually matter -- being padding bits, they're not meant to be accessed -- but zeroing them out could act as a security mitigation.
I don't know about the latter part of your statement being true or not. The former is due to looping usage so it's better to do bzero as the first operation for use instead of the last for reuse. In other words, don't do the same functionality in two separate areas.
the most common problem is that you write some code that dynamically allocates memory, you test it, it works fine, and then you write more code that depends on it, and later on (weeks, months, years) you run into some hard to reproduce bug
after a weekend of debugging it turns out your code only worked fine when you tested it because malloc was allocating freshly mapped pages the kernel had zeroed for you. so you didn't notice that you left some fields uninitialized in your records. ooops. you didn't need that weekend with your kids anyway
for this reason many debug allocators initialize your malloced memory as a form of offensive programming, and valgrind reports it as a bug if your program's behavior depends on uninitialized memory
In C's and Rust's model deallocated memory is assumed to be completely inaccessible (and Rust does its best to ensure it is inaccessible), so in a valid (non-UB) program there is nothing that could leak its secrets.
Also see "0 is special" by Linus https://yarchive.net/comp/linux/zero.html
(Zeroing out memory that you know you're going to overwrite is indeed wasteful because at least some of those pages will end up getting zeroed twice.)
Only if you can guarantee what free_and_zero() would succeed every time. But you can't.
Because reading from unitialized memory yields an indeterminate value. Operating on such a value can lead to UB. This applies to languages other than Rust too (e.g. C).
Ralf explains it better than me[1].
Since you mention Rust, here's a neat piece of trivia: `vec![0; N]` compiles down to a `calloc` call. (Well Rust's own version of `calloc`.)
If your allocation is about to take on a matrix that you will load from a default value or calculation for every cell - that would only suffer unnecessary latency if memory were zeroed on allocation.
But if your allocation is about to take on a struct with many fields and elements, it could be easily misused by not initializing every field (including when new fields are added), then a zero or other default initialization might be convenient.
Of course accessing not initialized fields can lead to catastrophic bugs, imagine for example a structure containing a pointer not initialized to NULL that points to a random location, or a char* field that doesn't have a null-terminator in it.
It's safer to 0 initialize everything, at least if you forgot to initialize something you have a predictable situation that is still better than the value of the field depending on what was there previously that is not deterministic.
Because we might want to read from it before we write to it. The simplest case is an array: unless we ensure that we write to every index before we read from it, we risk reading out (potentially sensitive) garbage data if we didn't calloc it.
People make mistakes and forget to do this and their program sometimes goes wrong in an unpredictable way. Maybe only going wrong when in production. It’s redundancy - most other fields of engineering do it, we seem to think it’s weird in CS.
Rust lets you do that.
let m: u32; // note: no mut
m = 5;
Even this is totally fine: let m: u32; // note: no mut
if true {
m = 5
} else {
m = 2
}
>I know rust considers uninitialized memory unsafe but I don't get whyIt is wildly unsafe, because the compiler has to be able to rely on the fact that memory slots it emits assembly code for actually use only those bits the compiler knows are in use.
For example, on ARM you have no registers < 32 bit. So the compiler has to use those registers for u8 as well, but it has to be sure that nobody actually sets the high bits, otherwise multiplication (etc) would do completely insane things and not at all what the program should have done.
Similarly, memory slots have a size that is a multiple of 8 bits (because the load/store instructions usually can load/store exactly 8, 16, 32 bits etc) and your type doesn't necessarily have exactly that number of possible inhabitants of the type (it would only be the case if number of possible inhabitants = 2^(8 n) where n is a natural number). Clearly, this is not possible to ensure in general.
Of course you have the compiler be totally defensive about it and issue masking instructions all the time--but that would make the resulting program slow.
Also, think of a bool. It has two possible values, right? But in C, any value that is not equal to 0 is defined to be true.
Now when the compiler emits code for a && b it can't do the obvious which would be
and r0, r1, r2
because that will do bitwise-and and let's say a = 4 and b = 1 then a bitand b = 0 but what you wanted is a && b == 1 since a is true and b is true. Worse if a = 5 and b = 1, it suddenly works.So that would be a bad idea as well (you'd have to emit extra instructions to check whether a is 0 and so on).
>Why is it important to initialize memory to 0's before we use it?
It's not. It's just C being C.
I'd actually prefer C to have an alloc function with two arguments m and n where it does m * n with overflow checking and then allocates that and then does NOT initialize the memory to 0's.
That said, todays computers are very fast and 0 has no data dependencies. So I wonder how much overhead, if any, in wall time, it adds to always zero out.
I guess, when writing in C, memset/calloc to 0 is a practical way to blanket-initialize all members of an object, say, pointer vars could then be safely checked against zero (NULL) to test whether it's been assigned or alloc'ed, strings emptied, counts zeroed, so would be flags. Convenient!
Basically, it's a shortcut with structured objects to avoid spelling out and initialising individual variables explicitly.
Why does calloc exist? - https://news.ycombinator.com/item?id=13108434 - Dec 2016 (132 comments)
we miss you on icb
> The calloc function returns […] a null pointer […] if the mathematical product of nmemb * size is not representable as a value of type size_t.
So apparently the Committee is OK with allocating more than SIZE_MAX/2 (but not more than SIZE_MAX).
The first argument that comes to mind is the existence of ptrdiff_t, but you’re not guaranteed to get a valid ptrdiff_t just by subtracting two pointers in the same array!
addr = base << 4 + offsetOn 16 bit x86, the biggest value processor can count to is 65535, but the number of those values (from 0 to 65535) is 65536, and so is the number of byte offsets in one segment. Memory handling functions had to deal with segment and offset calculations, overflows, underflows, and wraparounds in wider address space, and could allocate the full 64K segment when not limited by maximum value of a single variable (it was not guaranteed, though, as some allocators could reserve some space for their own headers). The value of 65535 was probably inherited as lower limit for SIZE_MAX in standard because 8 bit systems were not considered real targets for “real C” (as opposed to microcontroller-specific subsets of C). Of course, people then wrote C compilers for those systems, and various AVRs and STMs were made to support pointer-heavy and subroutine-heavy code better while still being simple.
One could get rid of those sharp corners by extending the compiler to present any system as having simple flat memory and integers that are big enough, but it would be the direct opposite of why people use C language. The performance would suffer, too.
Random oldnewthing link to make this comment seem well-sourced:
https://devblogs.microsoft.com/oldnewthing/20200728-00/?p=10...
At least for floating-point, not entirely sure about pointers.
2 63
T *foo = new T(1000);
> if we really cared about security we wouldn't be writing in C.
If we really cared about security we would definitely be writing in C.
If we really cared about security but would prefer not to think about it we wouldn'd be really caring about security, no matter the language.
Caring is done by little details. You don't want to risk with dangling pointers, do you? Then you either rely on someone else's work (garbage collector?) embedded in some "secure" language or you do your homework with careful memory allocation.
What about buffer/stack overflows? Same.
Finally, have you asked yourself with which language your "secure" stack (kernel, userland, compiler/ interpreter etc.) has been written?
I bet a huge part is in C.
Put another way, I trust the Rust code I write to be free of memory errors much more than I trust the C code that I write (despite having much more experience writing C than Rust). And yes, that's even accounting for the possibility of bugs in the Rust compiler that cause my program to do unsafe things with memory. Assuming I could actually maintain the focus and discipline to be my absolute most careful self every moment while writing C (which I, in reality, cannot), I still think the Rust compiler is safer than I am.
Frankly, I would consider nearly anyone (and possibly just an unqualified "anyone") who believes otherwise about their own abilities to be naive at best, and actively arrogant at worst.