Resume & Sample Code

LinkedIn Profile

Sample Code

This is a piece of program I wrote impromptu when I was interview by Google during my 2nd college year.

The task was to write a malloc function for data allocation less than 256 Bytes. My implementation ended up 100% faster than the native C malloc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/////////////////////////////////////////////////////
// Filename: newmalloc.c
// Author: Xiaotian Chen
/////////////////////////////////////////////////////
 
#include <sys/mman.h>;
#include <unistd.h>;
 
void* newmalloc(size_t size);
void newfree(void* p);
int inited = 0;
void* lastvalid;
 
struct Memhead
{
  struct Memhead* nextavailable;
  int size;
};
 
int headsize = sizeof(struct Memhead);
 
/* use a hashtable of size 31
* because after adding Memhead
* the sizes are at least 8 bytes long*/
struct Memhead* sizetable[31];
 
void init()
{
  int i;
  lastvalid = sbrk(0);
  inited = 1;
  for(i = 0; i < 31; ++i) 
    sizetable[i] = 0;
}
 
void newfree(void* p)
{
  size_t index;
  struct Memhead* ph = p - headsize;
  index = (ph->size/8) - 2;
  ph->nextavailable = sizetable[index];
  sizetable[index] = ph;
  return;
}
 
void* newmalloc(size_t size)
{
  int index;
  struct Memhead* retp = 0;
 
  if(!inited) 
    init();
 
  if(size == 0) 
    return 0;
 
  size += headsize;
  if((size%8)!=0) 
    size = (1 + size/8)*8;
 
  index = (size/8) - 2;
 
  while(index < 31)
  {
    retp = sizetable[index];
    if(retp != 0)
    {
      sizetable[index] = retp->nextavailable;
      retp->nextavailable = 0;
      break;
    }
    ++index;
  }
  if(retp == 0)
  {
    sbrk(size);
    retp = (struct Memhead*)lastvalid;
    lastvalid += size;
    retp->nextavailable = 0;
    retp->size = size;
  }
 
  retp += 1;
  return (void*)retp;
}
 
int main(int argc, char** argv)
{
  char* buf;
  size_t size = 150;
  int times = 0;
  while(times < 100000)
  {
    buf = (char*) newmalloc (size);
    newfree (buf);
    ++times;
  }
  return 1;
}