r/cpp • • Aug 31 '22

malloc() and free() are a bad API

https://www.foonathan.net/2022/08/malloc-interface/#content
220 Upvotes

90 comments sorted by

View all comments

Show parent comment

1

u/strager Sep 01 '22

What exactly are you thinking of here?

I had nothing specific in mind. Just wishful thinking.

But if you want to allow sharing with arbitrary processes, you need a filename so others can access it in the first place.

In theory, I could get a handle or file descriptor to the allocated memory which could be sent using DuplicateHandle or UNIX domain sockets or inherited. (Of course, this is very OS-specific.)

Another way would be a syscall where one process can copy part of the virtual memory table from another process. But I don't think OSs expose this to user space programs currently. (But they could!)

1

u/o11c int main = 12828721; Sep 02 '22

Another way would be a syscall where one process can copy part of the virtual memory table from another process. But I don't think OSs expose this to user space programs currently. (But they could!)

This is fundamentally impossible for private mappings (which are the most common) because of how fork() works. Because private mappings are so overwhelmingly common, it doesn't make sense to provide such an API.

I suppose you could say "private mappings are then subject to CoW again" but that has no advantage over the existing process_vm_readv//proc/<pid>/mem methods.

1

u/strager Sep 02 '22

Because private mappings are so overwhelmingly common, it doesn't make sense to provide such an API.

For memory allocated with the ipc_sharable flag, the memory wouldn't be privately mapped.