• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

how to implement malloc using C

Connoisseur

Platinum Member
so our linux programming professor throws this at us out of the blue. We're supposed to write malloc. Not just a function that calls the built in program but we're actually supposed to write the code for it... the only hint dude gave us was use sbreak... any clue? This is in debian linux btw.
 
http://www.cs.dartmouth.edu/~mckeeman/cs118/lectures/09.html

googling for "sbreak" didn't help much. I'm guessing sbreak is a pointer but I'm not quite sure where it's located or if that's its actual name code-wise.

I've never done this and have only vague knowledge of the subject, but I think it'd go something like:

1) malloc function takes nbytes as input
2) malloc makes a pointer to sbreak
3) malloc adjusts the real sbreak pointer forward by nbytes, since that area is now "used"
4) malloc makes a record somewhere internally that the pointer to this chunk of memory is nbytes long
5) malloc returns the pointer from #2

It gets a lot more complicated when you think that unlike the stack, the heap can have unallocated "holes" and isn't merely as simple to keep track of as one pointer. But I guess he did say implement malloc -- not free. So maybe you can be dirty and skip the bookkeeping (skip #4). Your malloc will leak everything it allocates, but hey, he did say to just implement malloc!
 
Does he actually expect your program to be able to use that allocated memory? If so you'll likely have to implement some OS calls.

If not just use a STL container to simulate a memory space and it should be a piece of cake.
 
Back
Top