4 ms·
Considering how much memory modern machines have, and considering she is running no other programs, I would be so tempted to write malloc like this just for gri
by sliverstorm 13y ago
Considering how much memory modern machines have, and considering she is running no other programs, I would be so tempted to write malloc like this just for grins:
int malloc() {
return rand() % TOTAL_MEMORY;
}
- jvns 13y agooh man that is the kind of bad idea that I love. I'm definitely going to try implementing malloc that way and report on the results =D
- TheLoneWolfling 13y agoMinor qualm: is rand defined?
- apgwoz 13y agoWell, rand can be defined as a Linear Congruential Generator (https://en.wikipedia.org/wiki/Linear_congruential_generator https://en.wikipedia.org/wiki/Linear_congruential_generator), or some other well known algorithm. LCG's don't require anything that the machine doesn't already do (mod, addition and multiplication)
- rca 13y agoYou could use rdrand if you're on (a recent enough) x86. You just lose some portability. Probably not a major issue at this point.
- munificent 13y agoYou jest, but you'd actually get surprisingly far just doing: void* malloc(size_t size) { static void* everything = 0; void* result = everything; everything += size; return result; } When people are hacking together VMs for garbage collected languages, the first allocator often looks like this until they get around to actually collecting the garbage.
- apgwoz 13y agoYou can get `free` pretty simply too: https://news.ycombinator.com/item?id=6849471 https://news.ycombinator.com/item?id=6849471
- stephen_g 13y agoDepending on how your memory is mapped, everything should probably be an address higher than the kernel (you can get your linker script to generate the right address). Sometimes the kernel is at the top of the address space though so you could start your heap at the bottom.
- MichaelGG 13y agoIf that's legal, then I'm confused over the problem. Why not just start with a single address and increase by the amount requested each time? It pushes any difficulty off to the implementation of free, right?
- sliverstorm 13y agoYou can do that. Of course you have to revamp it when you need to add 'free', but you can do it. It's just much less pernicious to do it that way, than my method, which means it's less fun :)
- MichaelGG 13y agoOK thanks for the info. I thought it was hard because he was in some mode that required him to setup pagetables and service faults and all that. So it's just hard because writing a decent malloc/free is involved, algorithmically.
- mercurial 13y agoIndeed, your method is a kind of malloc_roullette, depending on how much memory you allocate to the VM you run your kernel on.