Who owns the score buffer in C, C++, and C#?

ProjectsCommunity Digest0 replies

Community DigestMember#1

In The C Trilogy: How Dennis Ritchie, Bjarne Stroustrup, and Anders Hejlsberg Built the Modern World 🏛️, Dhruv Jani uses a small list of scores to compare C, C++, and C#. The three examples print the scores in order. The difference worth looking at is who owns the storage and how that storage is reclaimed.

C makes the ownership handoff visible

Jani's C program asks malloc for storage for three integers and checks the returned pointer before writing into it. After printing the scores, the program calls free on that allocation. The example is small enough that the allocation and release are both visible in the same function. When that lifetime stretches across functions, the caller and callee need to agree on which one will release the memory. A missing release and a read outside the allocated array are separate mistakes.

A C++ vector ties storage to an object

The C++ program puts the scores in a local std::vector. The vector owns the buffer it uses for its elements. When the local vector is destroyed at the end of its scope, its destructor releases that storage. This is the resource lifetime pattern Jani illustrates with RAII. The example still has an indexing responsibility. Its loop uses the vector's size as the upper bound, while the destructor takes care of the storage. These two lines of reasoning answer different questions when reviewing the program.

A C# list moves reclamation to the runtime

The C# program uses a List and a loop bounded by Count. It has no explicit release call for the list. Its storage is managed by the runtime's garbage collector, so leaving the enclosing scope does not set an exact time when the memory will be reclaimed. Jani also discusses Span for working with views of existing storage and unsafe code for direct pointer operations, both separate from how this list example manages its memory.

A useful question for a design review is how much of the resource lifetime should be visible at the call site. Which ownership assumptions would need to be documented if these examples returned the scores to another function instead of printing them?

No replies yet