Thursday, July 31, 2008

Resource control with scope guard

My friend Ozgur Macit asked me if there is a way to implement auto pointer design pattern for ANSI C functions like malloc and free.

Here is the traditional way to write a function:

int traditional()
{
char*ptr = (char*)malloc( sizeof(char) );

//check the return value if ptr is NULL or not

//use this ptr in several operations
//if statements, switch statements, pass as argument to other functions etc.

free(ptr);
return 0; //EXIT POINT

}

if function returns from the EXIT POINT, we all know that "free" function gives the memory back. However what if the function throws in the middle of the execution, or returns for some reason. Then we should handle all of these cases and write the free(ptr); statement before return points. This makes code less maintainable as well as more error prone.

Lets implement our scope guard class which will provide a safe and easy way to prevent this memory to be leaked.
What will we do is basically creating a local object which will be destroyed when it goes out of scope. That is way i call it scope guard.
It is clear that, when it goes out of scope, it should call "free" function with the necessary parameter.

class scope_guard{

void* _MyPtr;

public:
scope_guard( void* ptr ): _MyPtr( ptr ){}
~scope_guard(){ free(_MyPtr); }
};

It is pretty straightforward, isn`t it? It takes the pointer and frees it when local object goes out of scope.

Here is a simple usage:

int contemporary(){
char*ptr = (char*)malloc( sizeof(char) );
if(!ptr){
//log error message and return error code
}
//here we go..
scope_guard guard( ptr );

//use ptr in several operations...

return 0; //no explicit call to free. guard object will do this for us..
}

You should create the guard object after checking the malloc result and BEFORE using this pointer in any operations. Because semantic of creating a guard object is providing an error handling mechanism. if you use ptr in any operation before creating guard object and if this operation fails, you are in trouble now..

Note that the class i wrote here is a simple example for demonstration purpose. You can add template and function pointer concepts to this class to design a generic scope guard class which can work for lots of functions. Clearly, this one is craeted for only "malloc" and "free" pair.
You can also put copy constructor, assignment operator as private methods since they are meaningless in this case.

Thanks for reading this post, any comments will be appreciated.

Wednesday, July 30, 2008

Do you want to stop the time or do time travel to past?

This post dedicated to a non-computer science topic which is related to time. Time has a broad definition. Moreover if you think computer clock it is also a time. However todays topic is not too much related with computer clocks...

If you look at the subject, i mentioned about freezing the time and time traveling ?
Are these possible ? Can future`s technology let us go ? I will be trying to find some answers to these questions in this post.

Before reading the rest of this post please note that all these statements and ideas are mine and may be wrong or not. Don`t assume that what is written here is totally correct.

Before trying to finds an answer to time related questions, first lets define the time.
I have been thinking on this topic for a while. I think I am satisfied with my definitions. According to my opinion (i wont repeat this again since all ideas are my own truths) , Time is a "action" , "movement" , "motion" of an object or object groups. As you can see all these words are related with an energy of an object which makes "changes" on this object. In other words it changes the state of the object.

Indeed i haven`t looked at the literature definition of time (maybe it has the same definition). You may wonder, Why am i thinking like that? I will try to explain.

Before giving an example on a live object, i want to explain my thoughts on a simple object. Lets assume that our simple object is a "glass". Is time passing for the glass ? what is the meaning of time for this glass ? Let me explain..

If you apply a force to this glass and create a scratch on this, this glass will "change" its state. So "before" the scratch and "after" the scratch defines a time for this glass. ( Clearly, "before" and "after" are the words which are related with time).
Now, put this glass to a space. A space that no movement takes place in this space. No air ( no friction ), no waves inside it, nothing moves inside this space. All things remain static. Put the glass inside this and come back X years later. ( Note that you can not see the glass during this X year since there is nothing inside the space except glass. this means there is no photon! ). Glass is still the same glass if all things remain same inside the space during this X years. There is no concept such as time for this glass during this X years. How can it be? It is like freezing, no state changed, no events occurred, everything remains same like stopping the time for this glass! When you take it out of this space, time starts to pass again!

What about live objects? Can time also be stopped for them. If you go to such a space that we discussed for the glass, everything can be remain static except you! What does it mean? It means that, if you want to stop the time for you, you should stop breathing, your heart should stop beating, your eyes must not see anything, your ears must not hear anything. In other words, stop your neural system as well as other human systems. No impulse, no flow in your veins. This sounds pretty crazy, doesn`t it? I wont discuss if this is practicable or not. But these are the conditions that must be satisfied if you want to stop the time for yourself. I am not sure freezing your self like in the movies works for achieve this but if you are persistent give it a shot. let us know, if it works :)

If you read carefully, i am not talking about stopping the time by applying some mystic powers. You can not stop the time for other objects by your thoughts or your body energy. Some certain conditions must have satisfied.


So the answer to "is stopping the time possible" is yes. However some restrictions are applied. It is a experiment rather than experience.

In addition, my ideas are in the same page with relativity theory. I mentioned about stopping the time for certain objects. Time may be stopped for an object, but it is passing for other objects. One proof to my claim ( time is an "action" ... ) is that;
when you have no works to do, you are generally bored. You generally look your watch, time doesn`t pass quickly. 10 minutes may be like 1 hour. Do you know why? When you have no works to do, there is less action in your body. Less functionality, slow motions. So time becomes slower for you.
However when you are bored, your friend should be hurry, otherwise he miss the flight! He should prepare his luggage ASAP. Time passes quickly for him. Because he increase his "action". This is the relativity. Relativity is a difference between the velocity of two object actions.

Now, we answered one question. Lets look at the other one. Is time travel to past possible?
Since we have pretty much idea about the time now wen can answer this question quicker.

For returning back in time, you have to "undo" the actions. Can you revert an action which is already happened ? Answer is no. You can not revert it. What was happened was happened. There is no way to go back.

For explaining further, lets go back to our glass example. You scratch the glass and you are regretful now. You wish to go back in time and stop this event. You put the glass to our famous "space" to stop the time. everything is ok till now. You stopped the time for the glass, but how can you go back in time ? Once you stop all of the actions on this glass time is stopped for the glass. For reverting back, you should do some !magic!. Even if you have abilities to do some magic; if you do so, you will apply some action to that glass which causes to start the time for the glass.

So we have a pretty quick answer for time traveling. I am sorry, if i cause disappointments.

At the end of the day, you now have some ideas about time concepts.
Time is another dimension which consists of movements. If you want to stop it, you should stop the actions. If you want to revert it then good luck!

Wednesday, July 23, 2008

Avoid Memory Leaks with Auto Pointers

Hey Guys, i havent wroten a post for a long time.
Today i want to talk about Auto Pointers. It is a basic but powerful design pattern to prevent memory leaks.
When we are writing c++ programs we generally allocate some memory from heap and use it during the lifetime of a block/function/thread/process.. In most cases a careless programming causes leaking the memory. In case of an Exception or return statement we should give the memory back to OS, if we no longer need that heap area.

Let me introduce an example:

bool leak(){
char* pBuffer = new char[ MAX_BUFFER_LEN ];
// control , initialize or do smth with buffer
..................................

int rc = function1( pBuffer );
if( OK != rc )
return false; //Leak Memory

try{
rc = function2(); //function2 may throw
}catch( ... ){
return false; //Leak Memory
}

//Use buffer more
................................

delete[] pBuffer;
return true;
}

Obviously above function leaks memory if it returns false because of unsatisfied conditions or exceptions. If you are lucky your program just leaks the memory, but if system runs out of memory then your process will crash.

One way to avoid this leak is putting the delete[] pBuffer; statement to every return path. But this is not the best way, programmers may forget to do this or later another programmer may want to change this function and he may not have enough knowledge about all functions in big projects. Someone else can easily put a new return statement without releasing the memory. Besides that, code will become longer, if every return path contains resource cleanup statements.
Look at this:

bool leak(){
char* pBuffer = new char[ MAX_BUFFER_LEN ];
// control , initialize or do smth with buffer
..................................

int rc = function1( pBuffer );
if( OK != rc ){
delete[] pBuffer; //give memory back
return false;
}
try{
rc = function2(); //function2 may throw
}catch( ... ){
delete[] pBuffer; //give memory back
return false;
}

//Use buffer more (Another programmer may add new statements which may introduce new leaks
................................

delete[] pBuffer;
return true;
}


Auto Pointers make all this process easy. They are smart pointers which provides automatic memory deallocation.

now i am writing the same example with auto pointer:

bool leak(){
AutoVectorPtr pBuffer ( new char[ MAX_BUFFER_LEN ] );
// control , initialize or do smth with buffer
..................................

int rc = function1( pBuffer );
if( OK != rc )
return false;

try{
rc = function2(); //function2 may throw
}catch( ... ){
return false;
}

//Use buffer more
................................

return true;
}

So there are no delete[] statements, code is cleaner and more understandable. Even some other programmers add new return statements memory will never leak.
What is AutoVectorPtr ? It is a template class which takes a pointer to its constructor and deletes it in its destructor. Since it is a local object created in the function scope, it is guaranteed that it will be destroyed ( delete[] will be executed ) when function goes out of scope whether it returns or throws ( thanks to stack unwinding! )

Simple AutoVectorPtr is :

template
class AutoVectorPtr {

T* _MyPtr;
public:
AutoVectorPtr( T* ptr ) : _MyPtr( ptr ){}
~AutoVectorPtr(){ delete[] _MyPtr; }

T* operator()(){ return _MyPtr; }
};

Above is a simple AutoVectorPtr class for giving an idea what it looks like. It should also contain copy constructor, operator= and some more.
I named it as AutoVectorPtr because it makes operations on array. If it holds single item like int, char or any class object, we can name it something like AutoPtr.

There are some libraries which provide this kind of smart pointers.
Here is the wiki link: http://en.wikipedia.org/wiki/Auto_ptr