I've used malloc countless times, but as far as I know, reading and writing to memory that isn't expressly yours (which is in fact done by the malloc function) causes a segfault. If I wanted to make my own dynamic allocation functions my computer would probably just laugh at me and triple fault all the way to the moon and back. So why doesn't malloc generate segfaults? Does it have special permissions? If it doesn't, would it be possible to make my own malloc functions (which would be really cool)?

I'm not entirely sure what you're asking, but it sounds like you're questioning how malloc() works. In fact, it requests free memory from the operating system. Assuming the OS grants that request, malloc() now owns the memory and can do what it wants. Likewise, if malloc() succeeds then your program also owns the number of bytes you requested (which is almost assuredly less than what malloc() requested from the OS), starting at the pointer that you're given.

So the trick here is that malloc() doesn't work with memory that's assigned to your process, it works with memory specifically allocated using an appropriate system call. As a simple and pure example of deferring work to the OS, take a look at the malloc() implementation here and the underlying _sys_heapalloc() function here. Sorry, but you'll have to search as I didn't break the files down into a file per function.

I've used malloc countless times, but as far as I know, reading and writing to memory that isn't expressly yours (which is in fact done by the malloc function) causes a segfault... So why doesn't malloc generate segfaults?

For the same reason when you fly to Pheonix and rent a car the cops don't arrest you for driving a stolen vehicle. It is yours for the duration of the rental. So the memory malloc() gets is yours -- you basically rented it until either the program ends or you call free()

...it sounds like you're questioning how malloc() works.

I read it more as why malloc() works... ;o)

Edited 4 Years Ago by WaltP

Comments
I like that analogy. :)

If there's enough memory to be given why would a segmentation fault ocuur , also about writting your own malloc you can do it , it won't be that easy but doable .
writing my own malloc was my project last semster It didn't work great but I'm still working on it and it is fun.

If there's enough memory to be given why would a segmentation fault ocuur ,

If you ask for 20 bytes for the array prices and tried to access prices[20], you just tried to access memory you don't own. You only own up to prices[19]

also about writting your own malloc you can do it , it won't be that easy but doable .

Probably, if you understand how the operating system does things and have access and permissions to the proper O/S calls.

This article has been dead for over six months. Start a new discussion instead.