how to implement malloc using C

Connoisseur

Platinum Member
Sep 14, 2002
2,470
1
81
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.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
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!
 

BFG10K

Lifer
Aug 14, 2000
22,709
3,002
126
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.