[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.
Interview Questions and Answers :: Cisco

3. Write your own malloc, and free

Answer:

static unsigned char our_memory[1024 * 1024]; //reserve 1 MB for malloc
static size_t next_index = 0;

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *malloc(size_t sz)
{
void *mem;
pthread_mutex_lock
(&lock);
if(sizeof our_memory - next_index < sz){
pthread_mutex_unlock
(&lock);
return NULL;
}

mem
= &our_memory[next_index];
next_index
+= sz;
pthread_mutex_unlock
(&lock);
return mem;
}

void free(void *mem)
{
//we cheat, and don't free anything.
}

Post Your Answer Here:      Public      Private

Rate This: +0 -0
Report     

Post Your Reply Here:     

Report Error

Report Error

Please Login First Click Here