Saturday, October 9, 2010

Country Folks

I am writing this entry from a motel on Highway 26 in Blue Mountains. The thing about driving out of the city is that right about when the last building drops below the horizon, everything begins to slow down. The highway is no longer 100 km/h instead it drops down to 80 km/h. High-rises and malls with car noises and crowd chatter are replaced by corn fields and farmland with the music of birds and swinging flora. Instead of 100+ horsepower mustangs, these folks own the original 1 horse power mustangs, no oil change or gas needed, and instead of polluting the air it fertilizes the orchards.

After checking in to the motel we decided to go for a drive around the village which is approximately 15 minutes away by car. On the way to the village the traffic became very slow due to construction on the road. While I waited for the traffic to begin moving again I spotted a group of kids a few cars up the road armed with bags full of apples approaching the helpless cars. "Here we go again," I thought. "Why can't I go a full day without somebody trying to sell me something." As one of the youngsters approached my passenger window I prepared to signal to him that I wasn't interested, but just then the always benevolent and never 'arrrgghhhh' wife of mine opens the window. Fine! I fished in my pockets for a $20 to be prepared for whatever price this little creep would try to take us for. "Would you like some free apples?" asked the boy. Would I like some free apples? Are you kidding me who hands out free anything anymore, let alone free apples? In Toronto if you get offered something free it's most likely deepfried or illegal. I had to put away the 20 dollar bill in order to free my hand to be able to receive for free the very apple I did not want to buy. Who gives free apples away?

Later, on our way back from the village just off Highway 26 I saw a sign advertising honey at a good price. I pulled over and approached the little table by the side of the highway where the honey containers were. The table was in the front yard of a house whose owners I could not see anywhere. What was peculiar about this picture was that I didn't see anyone selling the honey. There, in front of me were several jars of honey and, most interestingly a topperware full of cash. Are you kidding me guys!? Really? Cash? Just lying around, no need for surveillance, or any sort of care? I must have stood in front of the table like a moron for about ten minutes trying to decode this unfamiliar situation. I kept thinking, "this is a trap man, they got snipers in the cornfields!. Touch those jars and you'll get shot. Just walk away..." Then, when I was about to get back in my car and drive the hell away, a smiling lady comes out of the house and waves at us. "Hi folks, just grab a jar and put the money in the box."
She must have read the confusion in my face for right away she said "You are from the city aren't you?"
I just could not believe that you can leave a box full of money and the product you are selling unattended, and not only not have it get stolen, but get the product to sell itself while the box swells up with more money from nice and honest customers. Mind boggling! Apparently however, this is just how business is done on this side of the country.

I love my high-rises, sport cars, and technology infested city-boy society, but it takes a few jars of self selling honey and a self guarding money box to poke a hole in our sophisticated cloud of egotistical realism, and realize that we need to preserve the country folks lest the world implode into a useless goo of materialistic bullshit

Thursday, September 3, 2009

Stack Growth - Stackoverflow

Stack Growth

Another question you might get is to try to figure out which way a stack grows. As we know a stack (memory region interpreted as a stack) gets allocated for each process. The stack is used to store local variables and context local to the process. Each function call in a process gets a frame inside the stack where the variables local to the functions get stored; when the function exits the frame gets freed. The stack is also used to store the address of the caller function so that the IP (instruction pointer) can jump back after exiting a function call. i.e:

From the example below (Program:) before main() jumps off into foo(), it first pushes the current address of the IP into the stack so that when foo finishes, the IP can know where to go back to in main();

In some systems the stack is said to grow up and in others it is said to grow down. What the heck does that mean? See bellow:

Memory:
0x00000004 -- -- -- --
0x00000008 -- -- -- --
0x0000000C -- -- -- --
0x00000010 -- -- -- --
...

Program:
int foo();
main();
main()-call->foo();

In a simplistic world (don't hold me to the number it's just an example) if your main()'s frame is at 0x0000000C and foo()'s frame is pushed onto the stack at 0x00000008 then the stack is said to grow down-even though in the diagram it might appear as growing up-because the addresses decrease in that direction. If foo() were to appear at 0x00000010 then the stack would grow up, or in the direction in which the addresses increase.

Code:

#include <stdio.h>

void stackTracer(int *x)
{
int y;
if(&y > x)
printf("The stack grows down\n");
else
printf("The stack grows up\n");
}

int main()
{
int x;
stackTracer(&x);
getchar();
return 0;
}


The code works because when stackTracer is called, the main() frame had already been created in the stack, therefore stackStracker() would be pushed onto the stack after main(). If the address of a variable declared in stackTracer() is greater that the address of a variable declared in main(), that tells you that the stack is growing up as it's growing in the direction that the addresses increase.

StackOverflow

The Stack has a size that is defined even before the process begins to run. The size of the Stack is defined by the linker and can be adjusted by changing the linker flags. But once the program has been linked with the Stack size then that will remain the size of the process' stack throughout its life time. Sometimes if you are not careful, you can grow the stack (recursion anyone?) over its allowed size; and you get a stackoverflow exception.

How can you tell the size of your stack?

This program came out of a couple of minutes of spare time when a co-worker friend of mine and myself decided to overflow the stack just for fun:

Code:


#include <stdio.h>

int counter = 0;
void crasher()
{
double array[10];
array[0]=1;
counter++;
printf("Counter is at %d", counter);
crasher();
}
int main()
{
crasher();
return 0;
}



Then to calculate the size of your stack do => counter (amount of times you allocated that array) * 8 bytes (the size of a double [check your system though]) * 10 (the amount of doubles in the array). Note: this will be roughly the size of your stack, to check the exact size you can always check the default for your linker or the linker flags.

Wednesday, September 2, 2009

Byte swizzling

So, we have all heard about little endian and big endian concepts. We all know that in a little endian system the least significant byte gets stored first, or at the lowest address. In a big endian system the most gets stored in first, or at the lowest address.

So what happens if you are trying to read data that has been stored in a big endian system?

Say you have 0xDEADBEEF stored like so:

Memory:
a => DE
a+1 => AD
a+2 => BE
a+3 => EF

if you have a 32 bit pointer address pointing to a+3 the value read will be 0XEFBEADDE. In order to make sense of the value you will need to swizzle it. In other words; you will need to change the order of bytes.

Here is code which will swizzle a 32 bit value:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define CODETOSWIZZLE 0XEFBEADDE
int main()
{

unsigned int swizzledCode = \
((CODETOSWIZZLE & 0x000000FF)<<24)\
+((CODETOSWIZZLE & 0x0000FF00)<<8)\
+((CODETOSWIZZLE & 0x00FF0000)>>8)\
+((CODETOSWIZZLE & 0xFF000000)>>24);

printf("Swizzled %x", swizzledCode);

getchar();
return 0;
}

Monday, August 31, 2009

Palindrome Test

The palindrome test is very common in interviews. Here is a program that shows how to find out if a string is a palindrome.

Please note that this a simple program as in an interview not much more is expected from you. The test is not meant to commercialize your greatest palindrome rendition. We will not be buying palindrome testing software in the near future. The point of this test is to know your basic knowledge of string manipulation and algorithm generation. This program takes a string and tests whether the string is a palindrome or not. The palindrome can be one word long, or a whole sentence, and can have upper and lower case letters. Note that palindromes are not case sensitive. Also, the palindrome should ignore punctuation marks.

Please note that in my simple algorithm I am assuming that regular ASCII characters are used.

Algorithm:

1) Get string and lets call it testItem;
2) Strip all the punctuation marks, spaces, and symbols,
and store in testItemClean.
3) Reverse the testItem and store it into reverse.
4) Compare testItemClean and reverse.

To find more about palindromes please visit here .


#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main()
{
char testItem[] = "Was it Eliot's toilet, I saw?\0";
int i = 0;
int currentPointer = 0;
int cPointerClean = 0;
int length = (strlen(testItem))-1;
char *reverse;
char *testItemClean;

reverse = (char*) malloc (length*sizeof(char));
testItemClean = (char*) malloc (length*sizeof(char));

for(i=0; i<=length; i++)
{
/*Reversing testItem and storing stripped
off symbols into *reverse*/

if((testItem[length-i]>=65 && testItem[length-i]<=90) \
||((testItem[length-i]>=97 && testItem[length-i]<=122)))
{
if(testItem[length-i]>65 && testItem[length-i]<90)
testItem[length-i] = testItem[length-i] + 32;
reverse[currentPointer] = testItem[length-i];
currentPointer++;
}

/*Stripping testItem off symbols and storing into
testItemClean*/

if((testItem[i]>=65 && testItem[i]<=90) \
||((testItem[i]>=97 && testItem[i]<=122)))
{
if(testItem[i]>65 && testItem[i]<90)
testItem[i] = testItem[i] + 32;
testItemClean[cPointerClean] = testItem[i];
cPointerClean++;
}

}
if(!strcmp(reverse, testItemClean))
printf("It's a palindrome");
getchar();
}

Bit counting (how many 1's in 5 [binary])

This code is simple and can be enhanced to work in more general cases. If you do end up changing any of the code and wish to post it, please feel free to do, but, do post a link back to this site.

Since so many of you have had problems in interviews regarding bit counting, I have decided to post this program. It counts the amount of 1's that there are in any 32 bit number.



#include <stdio.h>

#define BIT_MASK 0x1

int main()
{
int number = 52;
int i = 0;
int counter=0;
/*Looping for each bit in an int.*/
for(i = 0; i < 32; i++)
{
/*
RF1 -> Shift to the right by 1
52 is 110100 in binary.
Bitwise AND 0 with 1 ---> 0 -> RF1
0 with 1 ---> 0 -> RF1
1 with 1 ---> 1 increase counter -> RF1
0 with 1 ---> 0 -> RF1
1 with 1 ---> 1 increase counter -> RF1
1 with 1 ---> 1 increase counter -> RF1
...
It will continue 32 times except that
in this case (52) the rest will be 0s.
*/
if(number & BIT_MASK)
counter++;
number = number >> 1;
}


printf("The number of 1's in %d is: %d", number, counter);
/* Visual Studio will close the output window very fast.
This trick will keep it open.
*/
getchar();

}

Saturday, August 8, 2009

In Penang - Malaysia

So I have been in Penang - Malaysia for the last 3 weeks. I still have one more week to go. I am here on a business trip doing some embedded software development with Intel. And that's the most I am going to say about that.

I have to tell you, I am very impressed with Penang. When I arrived three weeks ago I wasn't sure about what to expect, or better yet, I expected different things. I had just returned from a business trip to Shanghai and while I loved the city and its people, I had some trouble getting used to the food. Being from Canada I am used to a different type of Chinese food. I arrived in Shanghai a month ago looking for chicken balls and sweet and sour chicken and instead found myself ordering from menus written completely in Chinese and having to pick based on pictures; and these sometimes deceive you. I learned towards the end of my trip that the taste of food I am more accustomed to is the Hong Konk style. So, while I was impressed with the explosion of modernism in high-rise, neon light, big screen Shanghai, and very thankful to the hospitality of its people, the trip left me worried about what to expect in Malaysia.

As soon as I landed in Penang I began to notice that most signs were written in English. Then, when I arrived at The Equatorial Hotel the whole 20 hours travel time began to look like it all might have just been worth it. But the Equatorial will be a subject of another post. This is just a look over Penang. I am very glad to say that most here speaks English very well. It is very easy to get around and I need not worry about getting lost. If I do, I get a cab and the driver will understand what I am saying. And the food...The food, as Robert from Everybody love's Raymond might say, "the food is unbelievable." The melting pot of cultures in Penang makes for an excellent dish. The most common restaurants are what the locals call Hawker places. These are food stands with a number of tables and chairs shared by all the stands. You walk and order the food you like from the different stands and tell them where you are sitting, they will then find you and bring you the food. In Hawker places you can find anything from Chinese, to Indian, to Italian food. As far as the food goes, I am doing very well.

Please keep tuned as I will keep writing about my Penang experiences.

Thursday, May 28, 2009

Driving north


Driving north is always entertaining. It doesn't matter what the compass might be yelling; pointing the righteous finger around, if there is farmland between here and there I call it north. That is because most of the time I don't know where north is. You see, I am pretty bad at directions. I don't blame myself, really. I blame communism and the U.S. I grew up in Cuba, you see? Cuba being an underdeveloped country did not have the proper means to manufacture compasses, and the U.S-created embargo made it impossible for me to get my poor young hands on a compass. The lack of compasses at an early age -- as explained by Dr. Marc Gebrauchsanleitung in Compass in early childhood-- rendered me unable to properly find my bearings in any situation. So, when you are out with me and get frustrated by my inabilites to find a location, don't blame me, blame the guys responsible for you getting a cheap vacation on pristine beaches.

In any case, I believe I started calling farmlands, north, because on the first occasion when I took a trip outside of Toronto deep into farmlands, it was to Oro Medonte; north of Barrie. Barrie, is north of Toronto. The other day I was driving north again--it might have been west-- and came to this little town before London Ontario. The outskirts of this little town are carpeted with miles of farmlands and mansion like houses. The main roads linking all these farms and towns are usually 8o km/h but I love driving at 45km/h and just admire the view. The houses look like mansions out of a Stephen King's movie. The gigantic estates where just one person lives, and inevitable becomes hunted. It's eerie and almost morbidly inviting.

In these small towns you can almost always find antic stores. I love going into these antic stores. It feels like taking the express train down memory lane. But insomebody else's memory. You find old chairs, old scratched tables with teeth marks so small and eroded that the kid that created them might be an old man by now. What always fascinates me is finding picture albums. Why people think I would buy their old pictures is always beyond me. But it doesn't mean that I still don't like browsing through. Perhaps it's that same morbid invitation. Most of the pictures are made crisp by the sun and age. They are yellow and faded at the edges of the shapes depicted in them. There are children in long shorts wearing classic tami beret hats and suspenders. The backgrounds look almost completely faded in all of them, but sometimes you are lucky enough to see some people in the odd park. You look at those people and you know that they are all dead, that everyone who was alive in that period: the mailman, all the mailmen, the bum, all the bums, lawyers, writers, family men, prisoners, teachers, every teacher in the planet, honest men, dishonest men, are dead. Yet, you are still looking at them. It's like a time telescope, and you get to peep through. You should try it sometimes when you are bored. Just drive north and see where it takes you, if you are like me it will take you to different places every time. Search for antic store, and look at the treassure hidden in them. Even colour faded roadsigns are sometimes interesting telescopes to look through.

I will give you one advise though, if you happen to be driving behind me on one of those streets make sure that you are polite and don't flash your lights at me. If you don't I will pull over and you can pass. If you do I will reduce my speed to 20km/h and we can both enjoy the view.