.dp-highlighter { font-family: "Consolas", "Monaco", "Courier New", Courier, monospace; font-size: 12px; background-color: #E7E5DC; width: 99%; overflow: auto; margin: 18px 0 18px 0 !important; padding-top: 1px; /* adds a little border on top when controls are hidden */ } /* clear styles */ .dp-highlighter ol, .dp-highlighter ol li, .dp-highlighter ol li span { margin: 0; padding: 0; border: none; } .dp-highlighter a, .dp-highlighter a:hover { background: none; border: none; padding: 0; margin: 0; } .dp-highlighter .bar { padding-left: 45px; } .dp-highlighter.collapsed .bar, .dp-highlighter.nogutter .bar { padding-left: 0px; } .dp-highlighter ol { list-style: decimal; /* for ie */ background-color: #fff; margin: 0px 0px 1px 45px !important; /* 1px bottom margin seems to fix occasional Firefox scrolling */ padding: 0px; color: #5C5C5C; } .dp-highlighter.nogutter ol, .dp-highlighter.nogutter ol li { list-style: none !important; margin-left: 0px !important; } .dp-highlighter ol li, .dp-highlighter .columns div { list-style: decimal-leading-zero; /* better look for others, override cascade from OL */ list-style-position: outside !important; border-left: 3px solid #6CE26C; background-color: #F8F8F8; color: #5C5C5C; padding: 0 3px 0 10px !important; margin: 0 !important; line-height: 14px; } .dp-highlighter.nogutter ol li, .dp-highlighter.nogutter .columns div { border: 0; } .dp-highlighter .columns { background-color: #F8F8F8; color: gray; overflow: hidden; width: 100%; } .dp-highlighter .columns div { padding-bottom: 5px; } .dp-highlighter ol li.alt { background-color: #FFF; color: inherit; } .dp-highlighter ol li span { color: black; background-color: inherit; } /* Adjust some properties when collapsed */ .dp-highlighter.collapsed ol { margin: 0px; } .dp-highlighter.collapsed ol li { display: none; } /* Additional modifications when in print-view */ .dp-highlighter.printing { border: none; } .dp-highlighter.printing .tools { display: none !important; } .dp-highlighter.printing li { display: list-item !important; } /* Styles for the tools */ .dp-highlighter .tools { padding: 3px 8px 3px 10px; font: 9px Verdana, Geneva, Arial, Helvetica, sans-serif; color: silver; background-color: #f8f8f8; padding-bottom: 10px; border-left: 3px solid #6CE26C; } .dp-highlighter.nogutter .tools { border-left: 0; } .dp-highlighter.collapsed .tools { border-bottom: 0; } .dp-highlighter .tools a { font-size: 9px; color: #a0a0a0; background-color: inherit; text-decoration: none; margin-right: 10px; } .dp-highlighter .tools a:hover { color: red; background-color: inherit; text-decoration: underline; } /* About dialog styles */ .dp-about { background-color: #fff; color: #333; margin: 0px; padding: 0px; } .dp-about table { width: 100%; height: 100%; font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; } .dp-about td { padding: 10px; vertical-align: top; } .dp-about .copy { border-bottom: 1px solid #ACA899; height: 95%; } .dp-about .title { color: red; background-color: inherit; font-weight: bold; } .dp-about .para { margin: 0 0 4px 0; } .dp-about .footer { background-color: #ECEADB; color: #333; border-top: 1px solid #fff; text-align: right; } .dp-about .close { font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; background-color: #ECEADB; color: #333; width: 60px; height: 22px; } /* Language specific styles */ .dp-highlighter .comment, .dp-highlighter .comments { color: #008200; background-color: inherit; } .dp-highlighter .string { color: blue; background-color: inherit; } .dp-highlighter .keyword { color: #069; font-weight: bold; background-color: inherit; } .dp-highlighter .preprocessor { color: gray; background-color: inherit; }

Sunday, July 22, 2012

Interview

Q: Shuffle a deck of cards (52 integers) - Microsoft

A:
///random shuffle of a pack of cards.
void shuffle(int arr [], size_t size)
{
srand(std::time(NULL));
for(int i = size - 1; size >= 0; --i)
{
int k = rand() % i;
std::swap(arr[i], arr[k]);
}
}


Q: Find if the binary representation of a number is a palindrome.
A:

bool is_palindrome(unsigned int a)
{
unsigned int j = 0;
unsigned int tmp = a;
while(a)
{
j = ( 1 << j ) | (a & 1);
a >>= 1;
}
return j == tmp;
}


Q: Convert a decimal number to its equivalent Roman Numeral.
A:
std::string toRoman(int n)
{
std::string r;

struct TO_ROMAN {
int num;
const char *str;
} to_roman[] = {
{ 1000, "M", },
{ 900, "CM", },
{ 500, "D", },
{ 400, "CD", },
{ 100, "C", },
{ 90, "XC", },
{ 50, "L", },
{ 40, "XL", },
{ 10, "X", },
{ 9, "IX", },
{ 5, "V", },
{ 4, "IV", },
{ 1, "I", },
};

for (int q = 0; q < sizeof(to_roman) / sizeof(to_roman[0]); ++q)
{
TO_ROMAN *t = &to_roman[q];

while (n >= t->num)
{
n -= t->num;
r += t->str;
}
}

return r;
}


Q: Implement sqrt function.
A: Using the NewTon method of approximation

///using NewTon's method
//make a guess: old_guess
//new_guess = (old_guess + value/old_guess) / 2
//if old_guess increases, the value/old_guess decreases
//however if old_guess increases, the value/old_guess decreases

double my_sqrt(double value)
{
const static double eps = 0.0005;
double old_guess = value / 2;
double new_guess = 0;
do
{
new_guess = (old_guess + value / old_guess ) / 2;
old_guess = new_guess;
double d = abs(new_guess * new_guess - value);
if( d < eps)
d = d;
else
d = d;
}
while( abs(new_guess * new_guess - value) > eps);

return new_guess;
}


Q: Reverse words in a string.
A:
void reverse_words(char * ptr)
{
size_t size = strlen( ptr );
//reverse all characters first
reverse_chars(ptr, 0, size - 1);

int word_start = 0;
int word_end = 0;
char* tmp = ptr;
while(*tmp)
{
word_start = word_end; //or eat up spaces
while(*tmp && *tmp != ' ') //assuming white space separator
{
word_end++;
++tmp;
}
//reverse each word. Do not use space.
reverse_chars(ptr, word_start, word_end - 1);
word_end++; //skip space. Assuming just one space.
++tmp;
}
}


Q: Amazon - Implement an algorithm to generate the prime numbers in the range 1 - 101
A:
void generate_primes()
{
const static int N = 101;
int numbers [ N ] = {0};

for(int i = 2; i <= N / 2; ++i)
for(int j = 2; j <= N / i; ++j)
numbers[ i * j ] = 1;

for(int i = 2; i < N; ++i)
{
if(!numbers[ i ])
std::cout << i << "\n";
}
std::cout << std::endl;

}


Q: Find if a string a is a substring of another string b.
A:
bool is_substr(const char* a, const char* b)
{
size_t size_a = strlen( a );
size_t size_b = strlen( b );

int j = 0, i = 0;
for( i = 0, j = 0; i < size_a, j < size_b; ++i, ++j)
{
if(a[ i ] == b[ j ]) //matching. Keep going
continue;

i = i - j; //return i to the next character after the prev match
j = -1; //reset j = -1, it'll become zero on loop increment

}
return j == size_b;
}


Q: Google - implement a memcpy function.
A:
void* my_memcpy(void * dst, const void* src, int size)
{
char* dst_ptr = (char*)dst;
const char* src_ptr = (char*) src;

while(size--)
*dst_ptr = *src_ptr;

return dst_ptr;
}


Q: Given a number (say, 7251), write a code to give the number of digits it has (i.e. 4 for 7251).

A:
int countDigits(int n)
{
int count = 0;
do
{
++count;
n /= 10;
}
while (n);

return count;
}

//second version. Find the dot and remove it from the count
int countDigits1(double n)
{
std::ostringstream ss;
ss << n;
return ss.str().size();

}



Q: Bloomberg LP: What is a seg fault? Show with code

A: Accessing memory that does not belong to your process. See my blog.

void foo()
{
char* p;
char c;

p = (char*) 0;
c = *p; //generates seg fault
}


Q: Bloomberg - //Bloomberg LP: What does this code do?
void bar()
{
int *p=0;
double *q=0;
printf("%u %u\n",p,q);
p++;
q++;
printf("%u %u\n",p,q);
}

A: It prints 0 0 4 8. First it initialize both pointers to NULL. Increment both pointers. First is int, increments by 4, sizeof(int), second by 8 (size of double).

Q: Amazon. Find out if a tree is a mirror of another tree

boolean isMirror(node1,node2){
if(node1==null){if(node2==null)return true; else return false;}
if(node2==null) return false;
if(node1.data!=node2.data)return false;
if(isMirror(node1.left,node2.right) && isMirror(node1.right,node2.left)) return true;
return false;
}


Q: Write a function that converts an integer into a hex string.
A:
std::string getHex(unsigned int num)
{
static const char* hex_values = "0123456789ABCDEF";
std::string ret;
int i = 0;
for(int i = 0; num; i++, num >>= 4)
{
ret += hex_values[ num & 0xF ];
}
//reverse string
std::string::size_type end = ret.size() - 1;
for(int i = 0; i < end; ++i, --end)
std::swap(ret[ i ], ret[ end]);
return ret;
}


Q: Implement addition without using any loops and without using +.
A:
int add(int p, int q)
{
if(q == 0)
return p;

int k, r;
k = p ^ q; //XOR is called addition modulo 2.
r = p & q; //this is the carry.
return add(k, r<<1);
}

Friday, December 25, 2009

Binding to member variables.

When we use boost::bind to bind to a member function, things are pretty easy. You're making a function object of a usually stand-alone or a member function. But when you bind to a member variable of a class, things get a little hazy. When binding to a member variable, usually, you get a member pointer to the type of the member variable. And if you are using this bind in the context of a STL algorithm, then you apply this data member pointer to the passed in argument. This makes absolutely no sense, but see the code below, and it will hopefully make more sense.


struct entry
{
typedef std::pair<int, bool> conn_type;
entry(int i, bool c) : conn_pair(i, c ) { }
// bool get_connecting() const { return connecting; }
conn_type conn_pair;
};

int main()
{
std::vector<entry> vec;
vec.push_back(entry(1, false));
vec.push_back(entry(2, false));
vec.push_back(entry(3, true));
vec.push_back(entry(4, false));


/// boost::bind(&entry::connecting, _1
/// Make a function object that willa lways return ***connecting***
/// member variable of the passed in object...
/// make a predicate that returns entry::connecting
/// create a member pointer. In this case of type
/// entry::*connectingPtr = &entry::connecting
/// returns _1.*connecting

if(std::find_if(vec.begin(), vec.end(), boost::bind(
&std::pair<int, bool>::second,
boost::bind(&entry::conn_pair, _1))) != vec.end())
{
std::cout << "Hey. Found one" << std::endl;
bool std::pair<int, bool>::*connectingPtr = &std::pair<int, bool>::second;
std::cout << std::boolalpha << vec.front().conn_pair.*connectingPtr << std::endl;
}

return 0;
}


And if you are one of those who think pointers to data members are not useful, think again. The benefit of them is that once you declare a pointer to point to a data member of a type, you can use on different instances of that type. This link explains it clearly: http://stackoverflow.com/questions/670734/c-pointer-to-class-data-member

int main()
{
int Car::*pSpeed = &Car::speed;
Car myCar;
Car yourCar;

//access different instances using the same pointer.
int mySpeed = myCar.*pSpeed;
int yourSpeed = yourCar.*pSpeed;

assert(mySpeed > yourSpeed); // ;-)

return 0;
}



You might argue that you can always add a getter function that returns to you the value you pointed to, and do without pointers headaches. Not so. Like I showed in the example above, sometimes you are using pre-existing classes, like std::pair, and have no better way to have succinct code, except to bind. Oh well.

Friday, September 4, 2009

Un-install a program programmatically (C++ on Windows)

Ever wondered how a program is uninstalled when we remove a program from the control panel? Every installed program stores an uninstallString which is a command to un-install itself in the registry. If you can locate your program by searching for its name (I am using the name 'My Program' here), or if you know the product code, it really is a piece of cake....

Here is a sample program to search the registry for a program called My Program and uninstall it.

#include <iostream>
#include <algorithm>
#include <string>
#include <windows.h>
#include <winreg.h>
#include <iostream>
#include <cstdlib>

bool uninstallMyProgram(HKEY hRootKey,const wchar_t *wzKey);

bool search(HKEY hRootKey, const wchar_t *wzKey)
{
const int KeyNameBufferSize = 512;

LONG result = ERROR_SUCCESS;
TCHAR keyName[KeyNameBufferSize];
DWORD index = 0;
DWORD nameLength = KeyNameBufferSize;
FILETIME lastWriteTime;

HKEY hRegKey;
if(::RegOpenKeyEx(hRootKey, wzKey, 0L, KEY_READ , &hRegKey) != ERROR_SUCCESS)
return false;

while (result == ERROR_SUCCESS)
{
nameLength = KeyNameBufferSize;
result = ::RegEnumKeyEx(hRegKey, index, keyName,
&nameLength, 0, NULL, NULL, &lastWriteTime);

if (result == ERROR_SUCCESS)
{
std::wstring str = wzKey ;
str += keyName;
if(uninstallMyProgram(hRegKey, str.c_str()))
return true;
}

index++;
}
RegCloseKey(hRootKey);
return (result == ERROR_NO_MORE_ITEMS) ? true : false;
}

bool uninstallMyProgram(HKEY hRootKey,const wchar_t *wzKey)
{
const int KeyNameBufferSize = 1024;
wchar_t valueBuffer[ KeyNameBufferSize ];
valueBuffer[0]=0;

DWORD dwType = REG_SZ;
BYTE abValueDat[ KeyNameBufferSize ];
DWORD dwValDatLen = sizeof(abValueDat);
HKEY hKey;

if(::RegOpenKeyEx(HKEY_LOCAL_MACHINE, wzKey, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
return false;

if(::RegQueryValueEx(hKey, L"DisplayName", 0L, &dwType, abValueDat, &dwValDatLen) != ERROR_SUCCESS)
return false;

wsprintf(valueBuffer,L"%s", (wchar_t*) abValueDat);
if(::_wcsnicmp(L"My Program", valueBuffer, 14) == 0)
{
wchar_t uninstallCommand[ KeyNameBufferSize ];
BYTE retValueDat [ KeyNameBufferSize ];
dwValDatLen = sizeof(retValueDat);

if(::RegQueryValueEx(hKey, L"UninstallString", 0L, &dwType, retValueDat, &dwValDatLen) == ERROR_SUCCESS)
{
::wsprintf(uninstallCommand,L"%s", (wchar_t*) retValueDat );
if(-1 == ::_wsystem(uninstallCommand)) //execute the command to uninstall My Program
{
RegCloseKey(hKey);
return false;
}
RegCloseKey(hKey);
return true;
}
}
RegCloseKey(hKey);
return false; //My Program is not installed
}

int main()
{
const wchar_t* path = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\";
bool removed = search( HKEY_LOCAL_MACHINE, path);
if(!removed)
removed = search( HKEY_CURRENT_USER, path);
}

Tuesday, August 11, 2009

Programming Interview Questions (2)

Q: Implement a k-reverse function for reversing the elements of a linked list.
A:
Nodeptr ReverseN(Nodeptr head, int number) {

if(number < 2)
return head;

Nodeptr pre_sub_list_tail = NULL;
Nodeptr curr_ptr = head;
Nodeptr reversed_list_head = NULL;

while(curr_ptr)
{
Nodeptr prev_ptr = NULL;
Nodeptr nxt_ptr = NULL;
Nodeptr sub_list_tail = NULL;
Nodeptr sub_list_head = NULL;

int count = number;
while(curr_ptr && count)
{
if(number == count)
sub_list_tail = curr_ptr;

nxt_ptr = curr_ptr->nxtptr;
curr_ptr->nxtptr = prev_ptr;
prev_ptr = curr_ptr;
curr_ptr = nxt_ptr;
--count;
if(curr_ptr == NULL)
sub_list_head = prev_ptr;
else if(count == 1)
sub_list_head = curr_ptr;
}

if(pre_sub_list_tail)
{
pre_sub_list_tail->nxtptr = sub_list_head;
}
else
{
reversed_list_head = sub_list_head;
}
pre_sub_list_tail = sub_list_tail;
}
return reversed_list_head;

}



Q: write a program to find the nth left-truncatable prime.
A:
#include <vector>
#include <iostream>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/optional.hpp>


///works for p > 2
///we check all single digit truncatable primes in nth_truncatable_prime function below
bool is_prime(long p)
{
for (long i = 2; i * i <= p; i = (i + 1) | 1)
if (p % i == 0)
return false;

return true;
}

boost::optional<long> nth_truncatable_prime(long nth_truncatable)
{
if(nth_truncatable <= 0)
return boost::optional<long> ();

typedef std::vector< long >::size_type size_type;
const size_type initial_size = 200;

std::vector<long> last_primes;
last_primes.reserve( initial_size );

using namespace boost::assign;
last_primes += 2,3,5,7;

if(nth_truncatable < 5)
return boost::optional< long > (last_primes[ nth_truncatable -1 ] );

///number of truncatable primes so far 4, i.e., (2, 3, 5, 7)
int truncatable_primes = 4;
const int max_power = 9;

///iterate through powers (10s, 100s, 1000s, etc.)
for(int power = 1, mult_factor = 10; power <= max_power; ++power, mult_factor *= 10)
{
std::vector< long > current_primes;
current_primes.reserve( initial_size );

///iterate through smaller powers inside the outer power (10s in 100s, 100s in 1000s)
for(int i = 1; i <= max_power; ++i)
{
///construct a new truncatable prime from previous truncatable primes
std::vector<long>::const_iterator itEnd = last_primes.end();
for(std::vector<long>::const_iterator itBegin = last_primes.begin(); itBegin != itEnd ; ++itBegin)
{
const long result = mult_factor * (i) + *itBegin;

if(is_prime( result ) )
{
++truncatable_primes;
if(truncatable_primes == nth_truncatable)
return boost::optional<long> (result);

current_primes.push_back( result );
}
}
}
last_primes = current_primes;
}
return boost::optional<long> ();
}


Q: Reverse a linked list
A:
//--------------------------------
//Reverse a linked list
void reverseLinkedList(node **head)
{
node* tmp = *head;
node* prev = NULL;
node* next;

while(tmp)
{
next = tmp->next;
tmp->next = result;
result = tmp;
tmp = next;
}
*head = result;
}


Q: Remove the characters in str2 which are in str1
A:
//------------------------------------
//remove the characters in str1 which are in str2
//untested
void stringRemove(char * str1, char * toRemove)
{
//put the in array
int a[256], index =0;
const static unsigned size = 2

for (int i=0; i < 255; i++)
a[ i ] = 0;

for (int i=0; i<strlen(toRemove); i++)
a[ toRemove[ i ] ]=1;

for (int i=0; i<strlen(str1); i++)
{
if ( a[str1[i]] == 1) // to remove
continue;
else
str1[index++] = str1[i];
}
str1[index] = '\0';
}


Q: Perform binary search on a sorted but rotated array.
A:
int binary_search(int sortedArray[], int first, int last, int key) 
{

if (first <= last) {
int mid = (first + last) / 2;
if (key == sortedArray[mid])
return sortedArray[ mid ]; // found it.
else if (key < sortedArray[mid])
return binary_search(sortedArray, first, mid-1, key);
else
return binary_search(sortedArray, mid+1, last, key);
}
return -(first + 1); // failed to find key
}
//-----------------------------
int rotate_search(int sortedArray[], int first, int last, int key)
{
if(first <= last)
{
int mid = (last + first) / 2;

if(key == sortedArray[ mid ])
return sortedArray[ mid ];

int sort_start;
int sort_end;

int unsort_start;
int unsort_end;

if (first < mid)
{
sort_start = first;
sort_end = mid;

unsort_start = mid;
unsort_end = last;
}
else
{
sort_start = mid;
sort_end = last;

unsort_start = first;
unsort_end = mid;
}
if (key < sortedArray[ sort_end ])
return binary_search(sortedArray, sort_start, sort_end - 1, key);
else
return rotate_search (sortedArray, unsort_start + 1, unsort_end, key);
}
return -1;
}


Q: Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.

int countDuplicates(int* a, int N)
{
int dup = 0;
for(int i = 0; i < N; ++i)
{
if(a[ a[i] - 1 ] == -1)
{
dup++;
continue;
}
a[ a[i] - 1] = -1;
}
return dup;
}


Q: Write a program to check whether the given two logical addresses are in the same page.

A: Since the page boundaries are at 0, 4, 8k …we can see that the page size is equal to 4K. Now assuming we have a 32 bit address space, bits 31-20 will always be the same for one block of 4k bytes of memory since 4k is equal to 4*1024 which is equal to 12 lower order bits of the address. Given two addresses the only thing to be checked is their bits from 31-20. If they are same that means both the addresses lie in the same page. (Assuming int size is 4 bytes else we will use long to store the address)

bool AreOnSamePage (int *a, int *b)
{
return (a & 0xFFFFF000) == (c & 0xFFFFF000);
}


Q: Count the number of SET bits in an integer
//Count the number of SET bits in an integer (32-bit)
//Method 1

unsigned int count;
for (unsigned int v = 0; v; v >= 1)
count += v & 1;

//a better way. Goes through the loop as many as there are set bits.
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}


Q: I want to see if all the ones in a number appear on the right side of the number and all zeros appear on the left, how can I do this most efficiently? (e.g, 00000111 is true but 100010 is false)

    On the right: (x + 1) & x == 0;
On the left: (~x + 1) & ~x == 0;


Q: Implement a function to generate fib sequence.
A:
unsigned int fib(unsigned int n)
{
if(n < 2)
return n;

unsigned int i_1 = 1;
unsigned int i_2 = 0;
unsigned sum = 0;
for(unsigned int i = 2; i <= n; ++i)
{
sum = i_1 + i_2;
i_2 = i_1;
i_1 = sum;
}
return sum;
}

unsigned int fibR(unsigned int n)
{
if (n < 2)
return n;
return fib(n - 1) + fib ( n - 2);
}


Q: Print a matrix in a spiral way (i.e., top row, right col, bottom row, left col)
A:
void printSpiral(int a[][6], int rows, int cols)
{
int topRow = 0;
int rightCol = cols - 1;
int bottomRow = rows - 1;
int leftCol = 0;

while(topRow <= bottomRow && leftCol <= rightCol)
{
//top left to right. TopRow Fixed
for(int i = leftCol; i < rightCol; ++i)
std::cout << a[ topRow ][ i ] << std::endl;

for(int i = topRow; i < bottomRow; ++i)
std::cout << a[ i ][ rightCol ] << std::endl;

for(int i = rightCol; i > leftCol; --i)
std::cout << a[ bottomRow ][ i ] << std::endl;

//left col. bottom to top
for(int i = bottomRow; i > topRow; --i)
std::cout << a[ i ][ leftCol ] << std::endl;

topRow++;
rightCol--;
bottomRow--;
leftCol++;
}
}


Q: Code to remove spaces from a string.
void removSpaces(char *s)
{
int i, j = 0;

for (i = 0; s[i]; i++)
{
if (isspace(s[i]))
continue;

s[j++] = s[i];
}
s[j] = 0;
}



Q: Merge two sorted arrays.

//untested
int* merge_arrays(int* dst, const int* src, int size_dst, int size_src)
{
dst = static_cast<int*>(::realloc(dst, size_dst + size_src) );

while(size_dst > 0 || size_src > 0)
{
if(dst[ size_dst ] >= src[ size_src ] )
{
dst[ size_dst + sirce_src ] = dst[ size_dst ];
size_dst--;
}
else
{
dst[ size_dst + sirce_src ] = src[ size_src ];
size_src--;
}
}
return dst;
}


Q: Implement preorder, post order and inorder traversals in a single algorithm

traverse(s)
{
if(s)
{
preorder_queue.add(s);
traverse(s->left);
inorder_queue.add(s);
traverse(s->right);
postorder_queue(s);
}
}


Q: Reverse bits in an integer...


unsigned int reverse_bits(unsigned int a)
{
unsigned int result = 0;
unsigned int tmp = a;
while(tmp)
{
result = ( 1 << j ) | (tmp & 1);
tmp >>= 1;
}
return result;
}


Q: implement in-place swap:

void my_swap(int& a, int& b)
{
a ^= b;
b ^= a;
a ^= b;
}


Proof: http://en.wikipedia.org/wiki/XOR_swap

Q: Print a tree level by level (BFS algorithm)
A:
//print a binary Tree level by level
//Essentially doing a breadth first search
void BFS(NODE *root)
{
if (!root)
return;

Queue q = new Queue();

q->Enqueue(root);
do
{

NODE *curr = q->Dequeue();
print(curr->val);

if (curr->left)
q->Enqueue(curr->left);
if (curr->right)
q->Enqueue(curr->right);

}
while (!q->Empty());
}


Q: Implement a function that returns true if a binary tree is a BST.
A:
/*
Returns true if the given tree is a binary search tree
(efficient version).
*/
int isBST2(struct node* node) {
return(isBSTUtil(node, INT_MIN, INT_MAX));
}

/*
Returns true if the given tree is a BST and its
values are >= min and <= max.
*/
int isBSTUtil(struct node* node, int min, int max) {
if (node==NULL) return(true);

// false if this node violates the min/max constraint
if (node->data<min || node->data>max) return(false);

// otherwise check the subtrees recursively,
// tightening the min or max constraint
return
isBSTUtil(node->left, min, node->data) &&
isBSTUtil(node->right, node->data+1, max)
);
}


Q: Count the number of SET bits in an integer.
//Count the number of SET bits in an integer (32-bit)
//Method 1

unsigned int count;
for (unsigned int v = 0; v; v >= 1)
count += v & 1;

//a better way. Goes through the loop as many as there are set bits.
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}


Q: Get the depth of a binary tree (recursively)
A:
int get_three_depth(Node* root)
{
if(!root)
return 0;

return 1 + max( get_three_depth(root->right), get_three_depth(root->left) );
}


Q: Get the depth of a tree iteratively
A:
void BFS(NODE *root)
{
if (!root)
return;

int depth = 1; //root has depth 1
Queue q = new Queue();

q->Enqueue(root);
NODE* nextLevel = NULL;
if(root->left)
nextLevel = root->left;
else if(root->right)
nextLevel = root->right;
else
return depth;

do
{
NODE *curr = q->Dequeue();
print(curr->val);

if(nextLevel = curr)
{
depth++;
nextLevel
}
if (curr->left)
q->Enqueue(curr->left);
if (curr->right)
q->Enqueue(curr->right);

if(!nextLevel)
{
if(curr->left)
nextLevel = root->left;
else if(curr->right)
nextLevel = root->right;
}

}
while (!q->Empty());
}

Monday, June 22, 2009

boost intrusive_ptr

boost::intrusive_ptr is one of the six smart pointer class templates provided by boost. It is interesting in that it is widely used as shared_ptr, but sometiems very useful. It relies on the stored object to provide its own reference counting semantics using two functions that must be called: intrusive_ptr_add_ref and intrusive_ptr_release. These functions take a pointer argument to the pointer that is to be managed and must be defined in the boost namespace, or if the compiler supports Koenig lookup, in the namespace where the arguments are defined.

Read more about intrusive_ptr here: http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/intrusive_ptr.html

Here is a simple Example I put together for myself to understand how this works.

First, this is a base class that provides reference counting support by defining the intrusive_ptr_add_ref and intrusive_ptr_release. functions.

#include <ostream>
#include <boost/checked_delete.hpp>
#include <boost/detail/atomic_count.hpp>

template<class T>
struct intrusive_ptr_base
{
intrusive_ptr_base(): ref_count(0)
{
std::cout << " Default constructor " << std::endl;
}
//only construct an intrusive_ptr from another intrusive_ptr. That is it.
intrusive_ptr_base(intrusive_ptr_base<T> const&)
: ref_count(0)
{
std::cout << " Copy constructor..." << std::endl;
}

///does nto support assignment
intrusive_ptr_base& operator=(intrusive_ptr_base const& rhs)
{
std::cout << " Assignment operator..." << std::endl;
return *this;
}

friend void intrusive_ptr_add_ref(intrusive_ptr_base<T> const* s)
{
std::cout << " intrusive_ptr_add_ref..." << std::endl;
assert(s->ref_count >= 0);
assert(s != 0);
++s->ref_count;
}

friend void intrusive_ptr_release(intrusive_ptr_base<T> const* s)
{
std::cout << " intrusive_ptr_release..." << std::endl;
assert(s->ref_count > 0);
assert(s != 0);
if (--s->ref_count == 0)
boost::checked_delete(static_cast<T const*>(s));
}

boost::intrusive_ptr<T> self()
{
return boost::intrusive_ptr<T>((T*)this);
}

boost::intrusive_ptr<const T> self() const
{
return boost::intrusive_ptr<const T>((T const*)this);
}

int refcount() const
{
return ref_count;
}


private:
///should be modifiable even from const intrusive_ptr objects
mutable boost::detail::atomic_count ref_count;
};




By inheriting publicly from intrusive_ptr_base, we make available the essential reference counting functions: intrusive_ptr_add_ref and intrusive_ptr_release. Notice that we defined these arguments in the base class, so we defined these arguments int he namespace where the parameters are defined, and the best way to guarantee that the compiler finds them is to put them as friend functions in the base class. We put them as friends to give them access to the private data members. Notice that if we defined them as member functions, they will take the *this pointer and they won't match the expected signature that boost::intrusive_ptr requires. The output statements provided in the class are just for debugging purposes.

To test it:

#include <boost/intrusive_ptr.hpp>
#include "intrusive_ptr_base.hpp"

class Connection : public intrusive_ptr_base< Connection >
{
public:
Connection(int id, std::string tag)
: connection_id( id )
, connection_tag( tag ) {}

Connection(const Connection& rhs)
: connection_id( rhs.connection_id )
, connection_tag( rhs.connection_tag) {}

const Connection operator=( const Connection& rhs)
{
if(this != &rhs)
{
connection_id = rhs.connection_id;
connection_tag = rhs.connection_tag;
}
return *this;
}

private:
int connection_id;
std::string connection_tag;
};

int main()
{
std::cout << "Create an intrusive ptr" << std::endl;
boost::intrusive_ptr< Connection > con0 (new Connection(4, "sss") );
std::cout << "Create an intrusive ptr. Refcount = " << con0->refcount() << std::endl;
boost::intrusive_ptr< Connection > con1 (con0);
std::cout << "Create an intrusive ptr. Refcount = " << con1->refcount() << std::endl;
boost::intrusive_ptr< Connection > con2 = con0;
std::cout << "Create an intrusive ptr. Refcount = " << con2->refcount() << std::endl;

std::cout << "Create an intrusive ptr. Refcount = " << con2->refcount() << std::endl;
std::cout << "Destroy an intrusive ptr" << std::endl;
return 0;
}


We notice that when we construct an object or assign to it, boost::intrusive_ptr calls our functions to increment the reference count.

boost::intrusive_ptr has the same memory footprint as a raw ptr, and can be constructed from any T* raw pointer.

Also, shared_ptr if not used carefully can cause subtle crashes and bugs as I already discussed in this post here. That is, you should never create two shared_ptr objects using the same raw pointer, if you do, the destructor for the controlled resource will be called twice when the shared_ptr objects are destroyed. Instead, copy the first shared_ptr object to create a second shared_ptr object that controls the resource. To avoid it, always create a shared_ptr from another shared_ptr that points to that resource already. But if we use an intrusive_ptr, that problem goes away.

So use intrusive_ptr....

Thursday, March 12, 2009

postmortem debugging (WinDbg)

We write high quality code, but a crash is always possible. So what do you do if it your program crashes? Simple, you analyze the crash dumps, find out where and why it is crashing and fix it. But, what if the crash is not repeatable? Be prepared. The best thing to do is to install a crash dump tool on the computer where the software is going to be run/tested.

When a program error occurs in Windows, the operating system searches for a program error handler to deal with the error. If the system does not find such a handler, the system verifies that the program is not currently being debugged, and if not, it considers the error to be unhandled. The system then processes unhandled errors by looking in registry for a program error debugger. An example error handler is dr watson.

To install Dr. Watson as your crash dump analysis tool, follow these simple instructions here

To install Debugging tools for windows as your crash dump tool, do the following:

  • Download debugging tools for windows from here
  • Install it into your folder of choice, example: C:\Program Files\Debugging Tools for Windows.
  • Register Debugging tools for windows as your default debugger, by running this command from the command prompt: "C:\Program Files\Debugging Tools for Windows\WinDbg" -i" You should see this message confirming that WinDbg is your postmortem debugger:


  • Run regedit (from start->run) and modify this key: HKLM\software\microsoft\windows nt\currentversion\aedebug. Change the value of the key Debugger (creating it if necessary) to the following:
  • "C:\Program Files\Debugging Tools for Windows\cdb.exe" -p %ld -c ".dump /ma /u C:\Dumps\Crash.dmp; q" -e %ld –g

Any dump files from any programs from now on, will be put in C:\dumps\ with a .dmp extension.

Now that you have the dump file, take the .exe and .pdb files of the crashing program, drop them in your code's output directory and double click on the .dmp file. Visual studio will open a dump project for you. Start debugging your program, and it will show you where it crashes. This assumes that you built your program with debug symbols and moderate optimization (or no optmization). If you don't know how to do that, well, ask Google.

Wednesday, March 11, 2009

Add code expiry for hacks in your projects

Sometimes we are under tight deadlines to finish things, and we are forced to put in some hacks and quick fixes int he code, hoping to fix them later and write them propertly. You can add \\todo comments, and other stuff to remind you, but there is nothing better than a compilation error after a certain date.

I found this bit of code online, and just modified it slightly. You can put a compilation timebomb in your code, and once a certain date passes, your code will no longer compile. You'll be reminded to fix what you wanted to fix.

An example is provided here:

#include <iostream>
#include <sstream>

void assert_fail(const char* expr, int line, char const* file, const char* function);
#ifdef WIN32
#define CUSTOM_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __FUNCTION__); } while (false)
#else
#define CUSTOM_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__); } while (false)
#endif //WIN32

/////////////////////////////
#define YEAR ((((__DATE__ [7] - '0') * 10 + (__DATE__ [8] - '0')) * 10 \
+ (__DATE__ [9] - '0')) * 10 + (__DATE__ [10] - '0'))

#define MONTH (__DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? 1 : 6) \
: __DATE__ [2] == 'b' ? 2 \
: __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? 3 : 4) \
: __DATE__ [2] == 'y' ? 5 \
: __DATE__ [2] == 'l' ? 7 \
: __DATE__ [2] == 'g' ? 8 \
: __DATE__ [2] == 'p' ? 9 \
: __DATE__ [2] == 't' ? 10 \
: __DATE__ [2] == 'v' ? 11 : 12)

#define DAY ((__DATE__ [4] == ' ' ? 0 : __DATE__ [4] - '0') * 10 \
+ (__DATE__ [5] - '0'))

#define DATE_AS_INT (((YEAR - 2000) * 12 + MONTH) * 31 + DAY)YEAR - 2000) * 12 + MONTH) * 31 + DAY)

#define UNIQUE_NAME( Y,M,D ) ReviewBefore##_##Y##_##M##_##D##_##line
#define REVIEW_DATE( YYYY, MM, DD ) (((YYYY - 2000) * 12 + MM) * 31 + DD)
#define COMPILE_DATE (((YEAR - 2000) * 12 + MONTH) * 31 + DAY)

#define REVIEW_BEFORE( YYYY, MM, DD ) \
static const struct UNIQUE_NAME(YYYY,MM,DD)##__LINE__ { UNIQUE_NAME(YYYY,MM,DD)##__LINE__() { \
assert( COMPILE_DATE < REVIEW_DATE(YYYY, MM, DD) ); \
} } UNIQUE_NAME(YYYY,MM,DD)##__LINE__

#define EXPIRED "This code has expired"
#define REVIEW_BEFORE_STMT( YYYY, MM, DD ) \
CUSTOM_ASSERT(COMPILE_DATE < REVIEW_DATE(YYYY, MM, DD) )

void assert_fail(const char* expr, int line, char const* file, const char* function)
{
std::cerr << "Code obselete" << std::endl;
std::ostringstream str;
str << "Expresion: " << expr << "\n"
<< "line: " << line << "\n"
<< "file: " << file << "\n"
<< "function: " << function << "\n";

std::cerr << str.str() << std::endl;
}

int main()
{
REVIEW_BEFORE_STMT(2000,1,1);
std::cout << COMPILE_DATE << std::endl;

return 0;
}

Wednesday, March 4, 2009

why use shared_from_this() ?

Why would you need to use shared_from_this on an object? As the name implies, if you want to pass a shared pointer to *this (pointer to current object), then you use shared_from_this.

What happens if you don't? Well, a scenario could happen where you wrap *this pointer in a smart pointer from a member function, expecting that to work just fine. But what happens when you do that is you create another shared_ptr to *this with reference count of 1. When this member function exits, the shared_ptr gets destroyed, and your *this pointer is deleted, causing the destructor of the object to be called.

An example will make this clearer:
#include <iostream>
#include <boost/shared_ptr.hpp>

class Bar;
void foo(const boost::shared_ptr<Bar>& ptr);

class Bar
{
public:
void process()
{
foo(boost::shared_ptr<Bar>(this));
}
void print() const {std::cout << "I am still alive!!" << std::endl; }

~Bar() { std::cout << "Uh oh... I am dead!!" << std::endl; }
};

void foo(const boost::shared_ptr<Bar>& ptr)
{
ptr->print();
}

int main()
{
boost::shared_ptr<Bar> sPtr(new Bar());
sPtr->process();
sPtr->print();
std::cout << "Just before leavnig main " << std::endl;
sPtr->print();
return 0;
}


When you run this code (fix any errors first), it'll crash. The reason being, when the function process exits, the temporary shared_ptr resets its refcount to 0, and the *this object gets deleted. Then when main tries to delete the object again upon exit, it crashes.

To fix this, we use shared_from_this(), which will simply make sure that we get a smart pointer *this instead of a raw pointer *this. Read more about it in the boost docs


#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

class Bar;
void foo(const boost::shared_ptr<Bar>& ptr);

class Bar : public boost::enable_shared_from_this<Bar>
{
public:
void process()
{
foo(shared_from_this());
}
void print() const {std::cout << "I am still alive!!" << std::endl; }

~Bar() { std::cout << "Uh oh... I am dead!!" << std::endl; }
};

void foo(const boost::shared_ptr<Bar>& ptr)
{
ptr->print();
}

int main()
{
boost::shared_ptr<Bar> sPtr(new Bar());
sPtr->process();
sPtr->print();
std::cout << "Just before leavnig main " << std::endl;
sPtr->print();
return 0;
}

Tuesday, February 10, 2009

boost multi-index container

I am usually lazy to write tutorial-like articles, or anything of benefit, but I try to put here just something plain, simple that might direct the reader, and myself as well, in the right direction.

If you've worked with data that needs to be sorted according to many criterias, then you have probably struggled with using multiple containers and multiple sorting functions/algorithms. Scenarios include displaying data sorted in different views, such as, files according to size, name, change date, etc.

Here is an example of the very powerful boost multi index container. As the name implies it enables you to have multiple indices into your container, which enables you to look at it anyway you desire.

Read more about it, and find more examples here



#include <string>
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>

using boost::multi_index::multi_index_container;
using boost::multi_index::ordered_non_unique;
using boost::multi_index::ordered_unique;
using boost::multi_index::indexed_by;
using boost::multi_index::member;

struct employee_entry
{
employee_entry( const std::string& first,
const std::string& last,
long id):
first_name_(first),
last_name_(last),
id_(id)
{}
std::string first_name_;
std::string last_name_;
long id_;
};


typedef multi_index_container<
employee_entry, indexed_by<
ordered_unique<member<employee_entry, std::string
, &employee_entry::first_name_> >
, ordered_non_unique<member<employee_entry, std::string
, &employee_entry::last_name_> >
, ordered_non_unique<member<employee_entry, long
, &employee_entry::id_> >
>
> employee_set;

//employee set.... multi-index
employee_set m_employees;


int main()
{
using boost::multi_index::nth_index;
using boost::multi_index::get;

typedef nth_index<employee_set, 0>::type first_name_view;
first_name_view& fnv = get<0>(m_employees);

fnv.insert(employee_entry("John", "Smith", 110));
fnv.insert(employee_entry("Fudge", "Hunk", 97));
fnv.insert(employee_entry("Tolem", "Bathi", 87));
fnv.insert(employee_entry("Anjal", "Sunfo", 75));
fnv.insert(employee_entry("Heidi", "Clark", 89));

///get employees sorted by id
typedef nth_index<employee_set, 2>::type id_view;
id_view& idv = get <2> (m_employees);
for(id_view::reverse_iterator it = idv.rbegin(), it_end(idv.rend()); it != it_end; ++it)
{
std::cout << it->first_name_ <<" "
<< it->last_name_ << ":"
<< it->id_ << std::endl;
}

const std::string str(40, '-');
std::cout << str << std::endl;

///get employees sorted by first name
typedef nth_index<employee_set, 0>::type fname_view;
fname_view& fdv = get <0> (m_employees);

for(fname_view::iterator it = fdv.begin(), it_end(fdv.end()); it != it_end; ++it)
{
std::cout << it->first_name_ <<" "
<< it->last_name_ << ":"
<< it->id_ << std::endl;
}

return 0;
}

Thursday, November 27, 2008

Grub error 22 nightmare

So two nights ago, while trying to free up some space on my windows partition, I just decided to remove the linux SUSE partition which I rarely use. So I launched up partition magic, and off I go. I deleted the Linux partition. When I started my machine again, the nightmare started...

Booting grub stage 1.5
Grub error 22

What happened is that grub is looking for linux startup files that are not there anymore. One way to resolve this is to startup your computer with a windows CD, go to the recovery console, and execute fixmbr, which should restore the original MBR, windows only. I have a Toshiba Sattelite A100 laptop which comes only with a recovery CD (no Windows CD), so I had no luck with that.

I had valuable data on my hard-drive and simply wiping it out was not an option. So I did some research online and finally resolved my problem using the following:

1- Install the Ultimate Boot CD (free from www.ultimatebootcd.com). Get the self-extracting EXE as it is smaller and installs faster
2- Extract the ultimate boot cd into an ISO image and use Nero or some other CD writing software to burn it onto a blank CD
3- Insert this blank CD into your computer and startup.
4- Click F-12 as your machine is starting up (or the equivalent on your machine) to go to the Boot Menue. Choose to boot from CD/DVD
5- Once in the command list of the UltimateBootCD (UBCD), choose filesystem tools.
6- Go down to the MBRtool and select it. You should see a screen like the following:


7- Choose Option 4: Work with a MBR ...
8- From the next screen select option 9 (write/refresh boot code). It will ask you what Hard disk you want to select, choose 0 (or whichever is right for you). It will ask you whether you want to work with it on a file/sector or original, select 0 for original. Or simply execute this command /RBC /DSK:0
9- This usually just takes a second. Once this is done, reboot your machine again and it should boot normally this time.

Tuesday, November 11, 2008

boost::any (2) - storing pointers in boost::any

We know that we can retrieve the value stored in a boost::any using one of the two overloaded boost::any_cast by either passing our any by reference or as a pointer. What if we store a pointer in boost::any?

The following example assumes the declaration from the previous boost::any(1) post:

int main()
{
typedef std::vector<boost::any> MixedContainer_t;
MixedContainer_t mixedContainer;

A* aPtr1 = new A(2);
A* aPtr2 = new A(3);

mixedContainer.push_back(aPtr1);
mixedContainer.push_back(aPtr2);

//would not work. What is stored at front() is a pointer to A
//and not an object of type A.
if(A* a = boost::any_cast<A> (&mixedContainer.front()))
a->print();

//we can even confirm it by testing the types
if(typeid(A*) == mixedContainer.back().type())
{
std::cout << "object at front() is a pointer to A" << std::endl;
}
//to get a pointer to it, we need to retrieve a A**, and pass
//the type of object we think stored at front as A*
if(A** a = boost::any_cast<A*> (&mixedContainer.front()))
{
std::cout << "pointer-> ";
(*a)->print();
}

}


Storing pointers in boost::any is problematic, because boost::any stores only a value of the pointer, and when the boost::any is destroyed, the only memory that is released is that occupied by the pointer, and not the memory it points to. That is, delete or delete[] is not called. What to do? Use smart pointers. As with standard containers, avoid using auto_ptr because of its 'weird' copy semantics.

#include <iostream>
#include <vector>
#include <boost/any.hpp>
#include <boost/shared_ptr.hpp>


class A
{
int value_;
public:
A(int value) : value_(value) {}
void print() const {std::cout << "A's value: " << value_ << std::endl;}
~A() {std::cout << "A(" << value_ <<") destructor" << std::endl; }
};

class B
{
int value_;
public:
B(int value) : value_(value) {}
void print() const {std::cout << "B's value: " << value_ << std::endl;}
~B() {std::cout << "B(" << value_ <<") destructor" << std::endl; }
};

int main()
{
typedef std::vector<boost::any> MixedContainer_t;
MixedContainer_t mixedContainer;

boost::shared_ptr<A> aPtr0(new A(1));
A* aPtr1 = new A(2);
A* aPtr2 = new A(3);

mixedContainer.push_back(aPtr0);
mixedContainer.push_back(aPtr1);
mixedContainer.push_back(aPtr2);

//and to retrieve the value from shared Ptr is simple
try
{
boost::shared_ptr<A> ptr = boost::any_cast<boost::shared_ptr<A> > (mixedContainer.front());
ptr->print();

}
catch(boost::bad_any_cast& bac)
{
bac.what();
}
//only the destructor of the A pointed to by shared_ptr is printed.
}

Sunday, November 9, 2008

boost::any (1)

Sometimes you might want to store unrelated types in the same container, and convey the data from one point to another without caring much about it's type. C++ containers are templated on the type and can only store objects of the same type in the same container. Traditionally, this problem has been solved by storing pointers to objects as void pointers, or using discriminated unions. The problem with these two approaches is that they lose type safety. You can access elements using the wrong type and causes disastrous results at run time with no errors from the compiler.

boost::any solves this problem. Internally boost::any uses a templates to create a wrapper class for the type you pass to it, and then create an instance of this class on the heap. It then manages retrieving the object inside using boost::any_cast safely.

Examples:

#include <boost/any.hpp>
#include <iostream>
#include <string>
#include <vector>

class A
{
int value_;
public:
A(int value) : value_(value) {}
void print() const {std::cout << "A's print: " << value_ << std::endl; }
};

class B
{
public:
void print() const {std::cout << "B's print" << std::endl; }
};

class C
{
public:
void print() const {std::cout << "C's print" << std::endl; }
};

int main()
{
typedef std::vector<boost::any> MixedContainer_t;
MixedContainer_t mixedContainer;

mixedContainer.push_back(A(1));

try
{
A a = boost::any_cast<A> (mixedContainer.back());
a.print();
}
catch(boost::bad_any_cast& bac)
{
bac.what();
}

//you can also retrieve the object via a pointer using the
//the overloaded boost::any_cast
if(A* a = boost::any_cast<A> (&mixedContainer.back()))
{
std::cout << "I can retrieve A by pointer" << std::endl;
}

boost::any a1 = mixedContainer.back();
if(typeid(A*) == a1.type())
std::cout << "last element is of A's type " << std::endl;


mixedContainer.push_back(B());
mixedContainer.push_back(C());

//push a string
std::string str("Hello World!");
mixedContainer.push_back(str);

void print_any(boost::any& element); //declaration
std::for_each(mixedContainer.begin(),
mixedContainer.end(),
print_any);
return 0;
}

void print_any(boost::any& element)
{
try
{
A a = boost::any_cast<A> (element);
a.print();
}
catch(boost::bad_any_cast& ex)
{
std::cout << "bad cast exception" << ex.what();
}
try
{
B b = boost::any_cast<B> (element);
b.print();
}
catch(boost::bad_any_cast& ex)
{
std::cout << "bad cast exception" << ex.what();
}
try
{
C c = boost::any_cast<C> (element);
c.print();
}
catch(boost::bad_any_cast& ex)
{
std::cout << "bad cast exception" << ex.what();
}
}




As you can see in the previous example, we can store any type in boost::any. Boost::any preserves the type and will not let you tamper with it without knowing the correct type. You can store pointers too, but retrieving pointers is a bit tricky and I'll discuss it in a later post. For now, we are interested in the two mechanism for retrieving the values stores in boost::any:

template<typename ValueType>
ValueType any_cast(const any & operand);

The argument is the boost::any we want to retrieve, and the ValueType is the type of the stored value. If the type does not correspond to what is stored in boost::any, then this version of any_cast will throw a bad_any_cast exception.

template<typename ValueType>
ValueType * any_cast(any * operand)


This overloaded any_cast takes a pointer to any, and returns a pointer to the stored value. If the type in the any isn 't Value_Type, a NULL is returned. There is also a version of this any_cast for const pointers.

Note the difference between the first mechanism where an exception is thrown, and the second where a null pointer is returned. Also note that we can use any of the overloaded any_cast exception to retrieve the value by either passing our argument by reference (to use the first mechanism) or value (to use the second) as we show in the preceding example:

    mixedContainer.push_back(A(1));

try
{
A a = boost::any_cast<A> (mixedContainer.back());
a.print();
}
catch(...)
{}

if(A* a = boost::any_cast<A> (&mixedContainer.back()))
{
std::cout << "I can retrieve A by pointer" << std::endl;
}



References:
- Introduction to Boost by Bjorn Karlsson
- the boost website

Wednesday, October 8, 2008

My master's research accepted for publication in TON

This paper is pretty much the jist of my master's research at Simon Fraser University, Canada. It has been accepted for publication ni the very prestigious IEEE/ACM Transactions on Networking. It is an extended version of a conference paper in ICNP. Here is the abstract and a link to it:


Abstract:

Abstract—Peer-to-peer (P2P) file sharing systems generate a
major portion of the Internet traffic, and this portion is expected
to increase in the future. We explore the potential of deploying
proxy caches in different Autonomous Systems (ASes) with the
goal of reducing the cost incurred by Internet service providers
and alleviating the load on the Internet backbone. We conduct an
eight-month measurement study to analyze the P2P traffic characteristics
that are relevant to caching, such as object popularity,
popularity dynamics, and object size. Our study shows that the
popularity of P2P objects can be modeled by a Mandelbrot–Zipf
distribution, and that several workloads exist in P2P traffic.
Guided by our findings, we develop a novel caching algorithm
for P2P traffic that is based on object segmentation, and proportional
partial admission and eviction of objects. Our trace-based
simulations show that with a relatively small cache size, a byte
hit rate of up to 35% can be achieved by our algorithm, which is
close to the byte hit rate achieved by an off-line optimal algorithm
with complete knowledge of future requests. Our results also show
that our algorithm achieves a byte hit rate that is at least 40%
more, and at most triple, the byte hit rate of the common web
caching algorithms. Furthermore, our algorithm is robust in face
of aborted downloads, which is a common case in P2P systems

Link to the paper

Saturday, June 7, 2008

Boost interview questions

- What is boost? And why is it useful?
- What is a shared pointer?
- What is the difference between shared pointer, auto pointer and intrusive pointer?
- How is shared pointer implemented internally?
- How would you convert from string to integer using boost?

#include
#include
#include

/*
Implement as simple a class as possible to pass the test case below.
If possible,
- use only a single container
- do not use a void pointer
- use any stl/boost/mpl algorithms that are of use
*/


class cNamedVariableContainer
{
public:
template
void manage(const std::string& name, T& varRef)
{
}

public:
void setValue(const std::string& namedVariable, const std::string& value)
{
}
};



int main()
{
cNamedVariableContainer nvc;

int myInt(0);
double myDouble(0.);
std::string myString("");

nvc.manage("int", myInt);
nvc.manage("dbl", myDouble);
nvc.manage("str", myString);

nvc.setValue("int", "43");
nvc.setValue("dbl", "123.8");
nvc.setValue("str", "hello");

std::cout << myInt << std::endl;
std::cout << myDouble << std::endl;
std::cout << myString << std::endl;

assert(myInt==43);
assert(myDouble==123.8);
assert(myString=="hello");

return 0;
}

Friday, June 6, 2008

Interview Questions -- London Finance IT

I have been interviewing for a C++ software developer position at some of the UK finest investment banks and hedge funds. Here I'll share some of the questions that I was asked in a series of posts. But to be fair, I won't mention the names of those companies.

Those are actual questions I have been asked:

C++ Questions:

1- When would you prefer passing a reference to a function than a pointer?
2- Where is the const keyword used in C++ and what does it mean in each of those places it is used?
3- What is a mutable variable? Why might we need one?
4- What is a dynamic cast? What is RTTI?
5- What is an exception? When would you use exceptions? And why are they better than retyrning error codes?
6- How are exceptions implemented in C++?
7- How can a function guarantee that its resouces are released if an exception is thrown in the middle? -- Use RAII.
8- What is an exception safe function? What are the three types of exception safety?
9- What is a dangling pointer? And how does it usually happen?
10- What is a memory leak? How would you go about fixing it?
11- What is polymorphism? Virtual functions? Virtual tables?
12- When do you need a virtual destructor? Why is it not a good idea to always use virtual destructors?
13- Why is it a bad idea to throw exceptions from a destructor?
14- What is a pure virutal function? Why might we need to use it?
15- When do we absolutely need a dynamic cast? What alternatives can we have to dynamic casts?
16- Can pure virtual functions have an implementation? Is it a good idea to give them default implementation? Why?
17- What is a design pattern?
18- Explain Observer, Singleton and Bridge design pattern?
19- What is an Agile development?
20- Why do we need operator overloading? What concerns might we have with overloading?
21- Assume we have four istances of the same class, A, B, C, and D. What is the minimum number of operators called for this operation A = B * C + D?
22- Which could be potentially faster: accessing elements of a 2D array column-wise or row-wise? i.e., traversing columns or rows?
23- How do you prevent an object from being copyable? When might you need to do that? And in this case, how do you prevent methods of this object from calling its copying functions? What errors might arise?
24- How does C++ name mangling work?
26- How is polymorphism implemented in C++?
27- Can we have static virtual methods? Why?
....

rest to follow as I remember them.

Thursday, April 3, 2008

كان زمان

جلس بوقاره وشيخوخته يروي لنا قصة حياته من بدايتها... كيف أنه كان طفلاً صغير لا يستطيع فراق أمه أو الإنفصال عنها للحظات، وظن حينها أنها جزء من حياته وستظل كذلك إلى الأبد... لكنه كبر وشب عن الطوق، وقضى الله على أمه الموت فماتت، لكن كان له عوضه بإخوة أقرب إليه من قلبه بين ضلعيه، كأنه معهم روح واحدة في أجساد متفرقة... أحبهم وأحبوه وظن أن لن يستطيع الحياة بدونهم، لكنهم أيضاً شبوا وتزوجوا وكبروا، ثم أخذ كل منهم وجهته وسافر بعيدا عن بلدته، وبدأ حياته الجديده مع أسرته وأبناءه... ثم جاء دوره هو فتزوج وأنجب من الأبناء والبنين خمسة كالبدور، رباهم هو وزوجته وظن أن هذه هي حياته إذا، وهذه هي السعادة بعينهاً... ماذا يريد أكثر مما أنعم الله عليه به؟ بيت يقيه برد الشتاء وقيض الصيف، ويستره وأهله، وزوجة مخلصة محبه وأولاد طائعين ، وبسطة في العيش والمال... لكنهم، أيضا، شبوا وكبروا كما شب وكبر هو قبلاً... جاء للبنات من يرضين دينهم وخلقهم فزوجهن جميعاً وذهبن من بين يديه، ثم تزوج أبناءه أيضاً وغادرو العش الذي مافكر يوماً واحدا في أن أيا من ساكنية يستطيع التنفس خارجه... غادروه ليبدأوا هم أيضا حياتهم الجديده... لم يطل الزمان على عشه الجديد، فقضى الموت على حبيبة قلبه وشريكة عمره فماتت، وبقي هو ينتظر رحمة الله ودوره في المغادرة إلى عالم أكثر نقاء وخلوداً، عالم تدوم فيه اللذات...

ترى في عينيه خبرة في الحياة وحقيقتها، وتحس من كلامه قناعته بحياته وبما أنجر وعذره لنفسه في ما قصر، وإستعداده للموت، بينما أنت الشاب تفزع من مجرد ذكر هذه الكلمة المخيفة المريبه، غير مدرك بأنه كان أيضا شابا مثلك وفي سنك يخاف الموت ويخشاه ويريد من حياته أكثر ما أعطته، لكنه اليوم قنع بعد أن عارك الحياة... أنت تخاف النهاية لأن لديك من العمر فسحة، ومن العمل والمتستقبل الكثير إن كتب الله لك أن تعيش كما عاش، لكنه قد تلذذ بكل لذات الحياة، ثم تجرع مرارة فقدها، وعارك الحياة ليعلم في النهاية أن لكل بداية نهاية، فأصبح قلبه خالياً من كل شئ إلا من رحمة الله.

هكذا هي سنة الحياة، لا شئ يدوم، جميلاً كان أو قبيحاً... وحياتنا لا تقاس بالأنفاس التي نجترها، والتي يجترها كل حي، وإنما بأعمالنا التي نقدمها لإصلاح دنيانا كخلفاء لله في أرضه، وبين يدي آخرانا... لا تجعل من عمرك عبئأ على عاتقك، تريد الخلاص منه بأي وسيلة، فعمرك رأس مالك، فلتكن أكثر حرصا أين وكيف ولمن وعلى من تصرفه، ثم بعد هذا كله فكر في إستمثار جزء كبير منه لرحلة طويلة وسفر شاق، لحياة الخلود... ومع هذا فلا تنس نصيبك من الدنيا ولكن قدر نعمتي الصحة الصحة والفراغ التي أسداها الله عليك...

إن تنعمت بلذة فإعلم أن لها نهاية فأحسن إستخدامها، وإن أصبت بمصيبة فإعلم أن لها نهاية أيضا فهون عليك.

هاقد ولى رمضان، تاركا ألسنة البعض معقودة من شدة الحزن، وألسنة آخرين تقول (رمضان ولى هاتها ياساقي ... مشتاقة تسعى إلى مشتاق)، وكيفما كان حالي أو حالك، لتكن هذه بداية جديدة لحياة أكثر عطاءً وحيوية، ولننظر إلى حياتنا كفرص على ظهر الأرض لفعل شئ بدلا من النظر إليها كعبء ثقيل نشعر بالسعادة مع كل جزء نقتله منها.. إن كنت طالباً فإجعل من تعليمك جهاداً و إملا قلبك وعقلك بالعلم، وإن كنت موظفاً أو عاملا فلتكن حياتك نموذجاً للعالم الذي تحلم به وتريد أن تراه... إن كان لديك وقت فراغ فلا تفكر بطريقة لقضاءه والتخلص منه، بل إنظر إليه ككنز يمكنك إستخدامه وإضافته إلى رصيد حياتك الذي يتناقص مع شروق كل يوم جديد، مالم تضف إليها أنت رصيدا آخر يجعل من الوقت الباقي لحياتك أحد المقاييس لحياتك وليس المقياس الوحيد.

أتمنى من الله أن نكون ممن غادرنا شهر رمضان بلا ذنب، وعيدكم مبارك

Friday, February 15, 2008

أن تحترق

أن تحترق هو أن تحس بحرارة في أحشائك، وبرد في أعضائك وأطرافك، وأن تعالج غصة في حلقك لا تقوى على الخلاص منها... أن تحترق هو أن تعد الثواني وتستمع لعقارب الساعة تقرع شوكاتها على الجدار، هو أن يطول الليل ويظلم كنفسك التي بين جنبيك.... أن تحترق هو أن يبلغ بك اليأس درجة تصبح فيها حياتك عبئا ثقيلاً عليك تتمنى الخلاص منه، وعندها تتمنى للحظة ما لو يقف كل شئ، الحركة والسيارات والضوء والضجيج والحيوانات والحشرات وأن يقف الكون... تتمنى أن لا تدور الأرض... أن تحترق هو أن تتمنى أن تغمض عينيك ثم تفتحها وترى نفسك في عالم آخر غير عالمك الذي تعيشة... أن تحترق هو أن ترى الزمان كذبة كبرى، لأن دقيقتك ليست كدقيقة الناس وساعتك تمر عليك كدهر بائس... لو يقاس الدهر بعذابات المتألمين اليائسين الكادحين أمثالك لإبيضت رءوسهم قبل المشيب



ما أتعسك وأشقاك وما أشد عناءك أيها المسكين. هل وصل بك اليأس حد تمنى الموت؟ أنت وحدك جزيرة لا يعيش بها إلا أنت فأعمرها بما شئت، أعمرها باليأس تعش حياتك يائسا أو أعمرها بالياسمين إن شئت تعش حياة حبورا ونشوانا في غبطة وسرور دائمين.... أن نور نفسك هو النور الوحيد في ظلمتها، هو نهارك، فقليلا من الأمل يبلغك شط الآمان، النفس يتبعه آخر والدقيقة تتلوها أخرى وما حياتك وحياة كل مخلوق على ظهر البسيطة إلا هرولة نحو مصير محتوم، كلنا سيجري وكلنا سيقز القفز تلك إلى المجهول، الموت لكن هناك من يهرول نحو النهاية مدركا تمام الإدراك أنه واصل لا محالة فيجعل من رحلته سفرا جميلا يعيشه ولا يستثقله، وهناك من يتعثر في الطريق من شدة اليأس ومن علمه بالنهاية فيتمنى لو تهرول النهاية إليه قبل أن يصل إليها فلا تكن من الصنف الثاني



حياتي فقدت كل معانها، لم أعد أعرف سببا واحدا للإستيقاظ كل صباح، أراني أكرر ما عملت كل يوم، وأفعل ما يفعل الآخرون علي أجد يوما تعريفا لنفسي أو ماهيتي أو لماذا أنا؟ بل لعلي أعرف يوما ما من أنا ومن أكون؟ أرى كل يوم يجعلني أقل حيوية، لا أطيق النظرإلى ما يستمتع الناس بالنظر إليه.... لا أطيق الأطفال... منظر الطفولة والبراءة يقززني وليس له أي معنى في قاموسي، كما أني لا أرى ما يراه الآخرون من جمال الحياة؟ كيف يكون الجمال داخلي كما تحدثني؟ إن كان الجمال في أنفسنا فلم نبحث عنه في الزهرة الأنيقة، والمرأة الجميله والمنظر الجذاب واللحن العذب؟ لم لا نجلس مع أنفسنا مثلا في غرفتنا، نغلق كل نوافذها وفي الظلمة الحالكة نجعل شعاع النور في أنفسنا وجمالنا الداخلي يضئ حياتنا؟ كذب كل ما يقولون... حياتنا ليست جميله بل كارثية بكل ما تحمل الكلمة من معنى، رحلة معاناة من المهد الى اللحد، نعمل ونكد أنفسنا وعقولنا في تمثلية يلعب كل من دوره ببراعة لأننا لا نصدق للحظة واحدة أننا ممثلون، لكنك إن كنت مكاني وتحترق مثل ما أحترق لرأيت قبسا من الحقيقة: حياتنا كذبة كبرى، وتراجيدية لا تنتهي، والفرق الوحيد بيني وبينك هو أنني أدرك ذلك بينما تنكره أنت



بل حياتك أنت وحدك كذبة كبرى وحياة كل إنسان هي ما يعيشه... أتظن شخصا تحت جهاز التنفس الإصطناعي لسنوات حي؟ الحياة ياصديقي لا تقاس بعدد الأنفاس التي نتجرها أو السنوات التي نعيشها وإنما ماذا نفعل بها... لكي تدرك لحياتك معنى يجب عليك أولا فهم ماهيتها وماذا تكون: حياتك وحياة كل إنسان على وجه الأرض هي ما نفعله في فترتنا القصيرة عليها، فإجعل من حياتك سمفونية تطرب الأسماع، أو شمعة تحترف لتضئ للآخرين دروب حياتهم... ثم ليكن هدفك الأسمى في هذه الحياة مرتبط بالعلوي، بالله، وليس بشخصك أنت، فروحك التي بين جنبيك ماهي إلا وديعة عندك إلى حين.... الجمال الخالد والمعنى الحقيقي لحياة الإنسان يجب أن لا يرتبط معنىً دنيوي ينتهي مع حياة الشخص، كالمال والجمال والشهرة والنجاح، بل يكون مرتبطا بالله الذي له الخلود أبد الدهر، عندها يكون معنى حياتك خالدا... لن تشعر بطمأنينة القلب وراحة البال إن كان سببها دنيوي لأن كل دنيوي زائل، لكنك إن غرست في ذاتك حب الله، وإشتشعرت عظمته، وخفت غضبه ورجوت رحمته فإن عندئذ تكون قد قنعت بأن حياتك على ظهر هذه البسيطة ماهي إلا مقدمة وإختبار لحياة أكثر خلودا، وستعمل حينها على بلوغ معنى الحياة اللازائل بعد موتك، ولن تلهث نحو النهاية بعدها، بل ستخطو خطوات واثق نحو البداية الحقيقه...

Tuesday, January 1, 2008

صناعة القائد: وأما من جائك يسعى

روي أن رسول اللّه صلى اللّه عليه وسلم كان يوماً يخاطب بعض عظماء قريش، وقد طمع في إسلامه، فبينما هو يخاطبه ويناجيه إذ أقبل عبدلله ابن أم مكتوم، وكان رجلاً أعمى ممن أسلم قديماً، فجعل يسأل رسول اللّه صلى اللّه عليه وسلم عن شيء ويلح عليه، وود النبي صلى اللّه عليه وسلم أن لو كف ساعته تلك، ليتمكن من ذلك الرجل طمعاً ورغبة في هدايته وعبس في وجه ابن أم مكتوم وأعرض عنه، وأقبل على الأخر، فعاتبه الله تعالى بقوله: (‏عبس وتولى أن جاءه الأعمى * وما يدريك لعله يزكى)... أدبه ربه بأحسن أدب وأعظمه فأحسن تأديبه، وجعله مفخرة الإنسانية جمعاء، ومثالها الأعلى في القيادة والريادة، . كان صلى الله عليه وسلم لا يفرق بين سيد قرشي وعبد حبشي. كلهم سواء في الإسلام فزوج متبناه زيد بن حارثه، من سيدة قريش زينب بنت جحش، وأسدى على سلمان الفارسي المللوك في الجاهلية هوية (سلمان منا أهل البيت)! القادة الحقيقيون لا يفرقون بين تابعيهم أو يحقروا شأنهم ولا يقفون عند مجرد إصدار الأوامر والنصح للآخرين بل ويتجاوزونه إلى حد الإعتقاد بخيريتهم و العفو عن خطاياهم والإشفاق عليهم منها وتحسس مواقع الخير في نفوسهم وتنميتها.

غالبا ما تنتشر بين بعض القادة ثقافة الطهرانية لذواتهم ودونية الآخرين وتخلفهم، فهم المتعلمون والمتنورون وغيرهم رعاع جاهلون ، عالة على المجتمع، وسلم يستعمله هؤلاء "القادة" (إن صحت تسميتهم بذلك) للتسلق نحو إرضاء كبرياءهم وإعلاء شأن أنفسهم... عندما نؤمن بخيريتنا وشيطانية الآخرين، أو عدم إحترامهم كأنداد لنا، فلن نكون قادة لأنه ببساطة لن يتبعنا أحد. وعندما نعتزل الناس لأننا أطهر منهم روحا، أو أذكى منهم عقلا، فإننا نكون قد إخترنا لأنفسها أسهل الطرق للهروب من واجبات القيادة وأيسرها مؤنة...

ألاحظ كثيراً بين طبقة مثقفينا ألسنة سليطة على أوضاعنا في بلادنا حتى أنها لتبدو ظاهرة متأصلة في تراثنا أن نفخر بكوننا أفضل من بني جلدتنا وأطهر منهم روحا وأطيب قلبا. بل ويتجاوز ذلك إلى حد توصيف الداء والدواء وتشخيص الأخرين بأبشع العلل والأمراض، فهم (الثعابين) ونحن الراقصين على رؤوسهم، وهم (شعب جاهل ومتخلف) ونحن (ذوي العقول التقدميه والمتنوره)، وهم (رعاع الناس) ونحن فخرهم وزينتهم، وما ننساه أو نتناساه دائما أن (أنفك منك ولو كان أجدع)، وأن لا أحد يملك الحق للحكم على أحد.... قد يكون القائد محقا بإيمانه بضرورة تغيير الآخرين وتثقيفهم والإرتقاء بهم إلى مستوى يمكنهم من رؤية ما يراه، لكن إحترام الناس والعطف على ضعفهم ونقصهم وأخطائهم هو الطريق الأوحد لتأليف القلوب حول القائد... كونك قائداً لا يعني أنك أفضل ممن يتبعونك، فقد يكون منهم من هو أذكى منك وأصلح للقيادة، وإن كان الله قد عاتب نبيه وحبيبه على الإعراض للحظات عن رجل أعمى، فكيف بمن يحقرون أممهم ويزعمون بعدها أنهم قادة مشفقون عليها من عللها ومخلصون في أعمالهم للرقاء بها. إن كان الله قد أنعم علينا بالمال أو الجاه أو السلطان أو العلم، فيجب أن لا ننسى أننا جزء من نسيج أمتنا، بحياتها نحيا ومن كل خلية وعضو فيها نستمد طاقتنا وقوتنا.

القائد العظيم يشعر كل من حوله أن قضيته قضيتهم، وهمه همهم، ليس لأنه قرأ ذلك في كتاب أو تعلمه من أستاذ بل لأنه يؤمن به إيمانا عميقا متأصلا في نفسه، فيعامل الآخرين سواء، مهما كانت منازلهم في نفسه، وعندها يشعر كل من حوله أنهم ليسو مجرد آداة في آلة لا يفهمون فيها شيئا، بل أنهم جزء لا يتجزأ من جسد حي إذا إشتكى منه عضو تداعى له سائر الجسد بالسهر والحمى...

ولكي يكون الطرح أكثر واقعية، فأحب أن أختم بهذه النقاط التي لن أتبعك (أو يتبعك غيري) بدونها...
لكي أتبعك:
* عاملني بإحترام
* علمني ما لا أعلم
* أقل عثرتي وتجاوز عن هفواتي وأخطائي
* أصغ إلي عندما أتحدث وتكلم معي
* قل لي الحقيقة، وعاملني كند، ولتكن أفعالك إنعكاسا لكلماتك
* كن كريما بوقتك، وخبرتك، ومعارفك، عندما أحتاج أيا منها عندها فقط أتبعك بعقلي ونفسي وأضحي من أجلك ومن أجل ما تدعوا إليه.

Wednesday, December 26, 2007

OS/Architecture notes...

1- What is a segmentation fault, and how does it occur?


First, a word about memory protection. Modern operating systems provide the means to control access to the memory system. A user process should not be allowed to modify its read-only text section. It should not be allowed to read or modify any of the code and data structures in the kernel. It should not be allowed to read or write the private memory of other processes. And it should not be allowed to modify any virtual pages that are shared with other processes unless all parties explicitly allow it (via calls to explicit interprocess communication system calls). Each process usually has its own private virtual memory space, which translates to disjoint or safely shareable physical memory pages.

Remember that in virtual memory systems, we have a Page Table, which contains Page Table Entries (PTEs). A page table entry contains the base address of a physical page in DRAM, or an allocated page on the desk.

Enough of Virtual Memory. The operating system adds three permission bits to PTE entries, called SUP (supervisor), Read, Write bits, and they correspond to root, read, and write privliges respectively. If during the address translation the calling process violates any of those priviliges, it'll generate a protection fault (i.e., segmentation fault)....

Take this example

int main()
{
char* p;
char c;

p = (char*) 0;
c = *p; //generates seg fault
--(1)

}

The line at (1) generates a seg fault because it is trying to read location zero, and when the OS checks, it can't find a page allocated at location 0, and generates a segmentation fault.

p.s. This was a really crude descrition, so don't rely on it completely.... Should allow you to google it better, at the very least.

2- How do you detect if an overflow happened in adding two unsigned integers?

If the result is less than any of the operands, an overflow has occured in the case of unsigned addition. If both x and y less than 2^w (where w is the number of bits, we have no overflow). But s = x + y ==> s >= x (or y). So if s is less than x, or s is less than y, then we have an overflow. This is because in case of an overflow, s = x + y - 2^w (wraps around). THis is because we had a carry on of one, which we can't store, so we decrement the sum by 2^w. And since y < 2^w, y - 2^w < 0, which means s < x, hence overflow occured.

3- I get a stack overflow error at run time, but I can't spot any large stack allocations?

C++ allows you to delcare variables anywhere in the code (almost), unlike C which only allows you to delcare variables at the beginning of a block of instructions. So check large array allocations in the middle of your function/block. For example:


void myFunction(int
iTinyFourByteInteger)
{
int tinyInt1;
int tinyInt2;

int tinyInt3;
....
....
....
//after tens of lines of code
int largeArray[65536];

}

What the compiler did was to inspect your code first, push all local variables on the stack, regardless of where they were declared, then start the executing the first instruction in the function. If you're stepping through a debugger, you won't be able to spot the problem because it'll crash at the opening brace.

Sunday, December 23, 2007

Networking Interview Questions Cont.

These are some of the commonly asked, and not very well answered, questions:

What are the main differences between TCP/UDP?

  • UDP has no connection establishment. TCP has three way handshaking (send SYN, receive SYN-ACK, send ACK), while UDP has no connection establishment, hence called connectionless transport protocol
  • TCP keeps Connection state at the end systems, UDP doesn't. The This connection state includes receive and send buffers, congestion control parameters, and sequence and acknowledgment number parameters.
  • TCP has a 20-byte segment header overhead, while UDP has 8 segment header overhead.
  • TCP has a regulated send-rate. TCP has a congestion control mechanism that throttles the sender when one or more links between sender and receiver becomes excessively congested. This throttling can have a severe impact on real-time applications, which can tolerate some packet loss but require a minimum send rate. On the other hand, the speed at which UDP sends data is only constrained by the rate at which the application generates data, the capabilities of the source (CPU, clock rate, etc.) and the access bandwidth to the Internet.

2- What is Connected UDP?

Usually when creating a UDP socket we say:

socket = socket(PF_INET, SOCK_DGRAM, 0); //socket(family, type, proto)

Then to send using this socket we use:

ssize_t sendto(sock_fd,
void* buf, size_t nBytes,
int flags,
const struct sockaddr* to,
socklen_t len); //ssize_t is how much data the OS accepted to send.

If we use a udp socket in a call to connect, we create what is called connected UDP. This simply tells the OS the address of the peer; no handshaking is necessary and no data is sent to establish that the peer exist (i.e., no data is sent as a result of calling connect() on a udp socket. Why use it? If we communicating with a single peer, this might be useful since:

  1. We can call sendto() with null destination address
  2. We can use write() and send()
  3. We can use read() and recv(), which will return only data from the remote peer we connect()ed to.