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.

Monday, April 6, 2009

Commute on a rainy day

Today I woke to a rainy, snowy day. In the west end of city where I live, the wind was blowing fiercely and even under the multitude of blankets and sleep covers, I could hear the muffled roar of the wind outside my window. I threw a tired arm out from under the blankets and manged to grasp the remote control of my zenith tv resting on my night table. I turned on channel 7, Breakfast television, and listened to Frank Ferragine describe the forecast for today. Was it 25 mm or 25 cm of rain that it was going to fall today? I don't remember. But since it referred to rain I believe it must have been 25 mm. Then, tomorrow 8 cm of snow. Awesome!

I sat up in bed, listened to some more news. Watched Jennifer on the live eye tell the news on the fashion show at George Brown college; great show. Great models. I mean professionally, stop it! Then got up, showered, got ready and went to work. As soon as I got out of the building the wet damp snow falling on my head, and face made me realize one thing, the commute would be a pain. From where I live it normally takes me about an hour and fifteen minutes to get to work downtown. Usually at eight in the morning the subway and bus routes are bearable if not half empty, which is just the way I like it. However, when it rains or snows it seems as though the city swells in population. I don't know how it happens, but I believe it's a conspiracy. Yes, I believe the city has a conspiracy to ruin my mornings. I believe everyone congregates at city hall the night before it's going to rain, and think up ways to annoy me in the morning. Let me tell you, it actually works.You might think it's the nut in me talking, but why else would so many people come outside, just when I am outside, the days when it's cold, and damp and gray, and dark?

From my bedroom window I can see the 427 South with a line of cars squeezed bumper to bumper, and I know that they will remain bumper to bumper towards the Gardener Express Way and the exit on Yonge street. So, I choose not to drive downtown when it rains. I decide instead to take the bus, and the subway. But guess what, it's also full of conspirators pushing and closing up against me. You can all tell me your reasons of why both the highways and the transit systems get packed, and I am sure they are all reasonable excuses. I know the truth though. It's a conspiracy.

Today as it was to expect the subway was overflowing with passengers. On the Bloor Street line people were elbow to elbow as cars would be bumper to bumper on the surface. The next great thing about a subway ride with these many people is the festival of smells that erupts. As soon I thought of it as a festival, the image formed in my head, and in my mind it went something like this:

Narrow wet damp streets were suddenly formed between canvas tents with blue plastic tarp roofing tide at the corners with rope. Suddenly, a cacophony of loud marketeer screams exploded.

"Cigarette butt and Channel No. 5!" A well dressed business looking woman in the tent beside me was screaming.
"Cigarette butt and Channel No. 5, here for free! Only today! Do not miss it! Just for today, because it's rainy and gray, and ugly!"

Then from another tent a little to the left of this one someone else was screaming louder. "Stale coffee and sweaty armpits. Stale coffee, and sweaty armpits everyone! Don't miss it! Only while it rains!
"Every one gather around, stale coffee and sweaty armpits!"

Meanwhile in a very small tent in front of me a blond girl with pale blue eyes and a U of T bag pack was looking up and whispering "Acqua di Parma. Acqua di Parma, " but no one could hear her.

Now, in the dynamic marketplace the cigarette butt and Channel No. 5 tent had merged with the stale coffee and sweaty armpits tent and together had made a powerful enterprise which was slowly driving every marketeer out of business.


Just then from the far right an hysteric cry silenced all others. All the other tents disapeared. There was no festival anymore. Just one person. Standing in an open road. He was wearing a suit. He was holding a briefcase. He was looking at his watch. He was annoyed. He was upset. He was late. "Baad breaaath! Baad breaaath! Baad Breaath!" Screaming in my head like a fire alarm.

Thankfully just then my stop came and I got off before I got a headache. But as I walked up the stairs of the Yonge and Bloor subway station I could still smell some of the products the festival was giving away, and I wondered if by chance they had left me with a few samples.