Labels

  • Cpp and Windows stuffs
  • Home
Showing posts with label Cpp and Windows stuffs. Show all posts
Showing posts with label Cpp and Windows stuffs. Show all posts

Saturday, September 13, 2008

std::vector and pointers.


STL vector is nice class , which allows us to randomly access any location in the vector.

But if you use pointers to reference memory inside the vector , it can be dangerous depends upon the situation.

Consider this example, I have declared a std::vector object for storing some objects of "SomeClass".

std::vector<SomeClass> Objects;
// i am feeding the vector here... like Objects.push_back( .. )

 After feeding the vector i just took the address of first object in the vector.

like SomeClass* pThink = &Objects[0];

This is fine and has no problems at all. But the problems will come if you keep feeding the vector or removing elements .. Because std::vector will always reorganizing memory .It make sure that the memory allocated for objects will be continous.

So if we refer the pointer 'pThink' after push/ remove functions , it can cause expcetion similar to pointing incorrect memory location etc.


Wednesday, July 23, 2008

Checking a point inside Quadratic curve


In the last post I had written about qudratic equation. After that one thought came to my mind is How to check a point inside the curve ?. 


Below shows the qudratic curve equation from our 3 points. t^2(p1-p0'-p0) + p0' * t + p0 = P.  P is a point on the curve corresponding to t.


That is  a*t^2 + b* t + c = p, where a,b,c ,p are vectors. p yields the points on the curve accoding to the 't'.


So how can we check a point is in curve or not ?  we have 'p' and equation of the curve.As you guess this can be done by equation solving.But here a,b,c, are vectors.


So there must be some way to produce scalar values from these vetors , like taking magnitude of vectors in the equation like 


     |a|*t^2 + |b|*t + |c| = |p|.




This equation has some problmes , because it is just looking the magnitude of the vectors , direction is missing.A More wiser solution may be to solve for X,Y (Z in 3D)independently,like




a.x* t^2 + b.x *t + c.x = p.x --------> (1)


a.y* t^2 + b.y *t + c.y = p.y --------> (2)



As we know when we draw curve from p0 to p1 the t will vary from 0 -1 , We can check a point is inside the curve by solving one equation ( example : equation 1 ) and substitute that value of t in other equation ( here in equation2 ) . If you got the correct result as that of the input point (res == p.y) you can say the point is in the curve. Otherwise not.

When you solving the above equation you will get two values of t , so take the value which is inbetween 0 and 1 , and susbstitue it in other equation. 


To solve linear equation in computer you can use gauss elimination method ( you can try the above method in matheamtica easily ). 

Tuesday, January 29, 2008

C++ overloading operator& ( Or Find the addess of a object)

Recently a friend of mine ( name : rejeesh ) asked me "how to find the address of an object if the & operator is  overloaded" ?

Example class is like this

class AddressBlocker
{

public:

  AddressBlocker*
  operator &()  {  return 0;  }
};


so if you try to execute a code like this

AddressBlocker op;
AddressBlocker* Pt = &op;

Pt will be NULL. Pt =  &op will not pass the  real address of op to Pt. Because the operator is overloaded.

So how to get the address ??

When he asked me it, i found two solutions with templates .  One deriving a new class from the required class , and the second one is
more tricky. I will explain ( by showing the code) here both two methods.

Method 1.

template<typename T>
class Addressfinder : public T
{
public:
    Addressfinder* operator&() { return this; }
};

and you use it like this
AddressBlocker
blockMe;

Addressfinder<AddressBlocker>& finder = static_cast<Addressfinder<AddressBlocker>&> ( blockMe );


and address can be retrieved by simple  "AddressBlocker* pValid = &finder;" . This will work since i overloaded the &operator in Addressfinder class.
Method 2.

I think this is more good compared to the above. Since it is not creating any more relationships with the classes. and also no need for casting to use it.

template <typename T>
class AddressfinderII
{
    T& tOb;
public:
    AddressfinderII(T& t): tOb(t){}
    T * operator&()
    {
        return reinterpret_cast<T*> ( *reinterpret_cast<int *>( this ) );
    }
};

usage is like this

AddressBlocker blocker;
AddressfinderII<AddressBlocker> finderII(blocker);AddressBlocker * pAddress = &finderII;

if you look the size of this class , it just 4 bytes. because storing reference is same as pointer.
The class object's memory will have just the real address of object. And i extracted that value in operator& and returned.

Ok.. There is a more convenient way , he told me . and it is used in boost libraries. anyway i could find some alternatives 

Method 3

template<typename T>
T* addessof(T& t)
{
    return reinterpret_cast<T*>(& reinterpret_cast<int&> ( t ) );
}

and can be use like addressof( blocker); it is more convenient. it has similarities with method 1. So now no more address hiding..


Wednesday, December 12, 2007

Reducing Heap Fragmentation with Low Fragment Heap Featuer


Today most pc have enough memory . But there is still chance to occur fragmentation by continuously allocating and freeing small chunk of memory.

Windows Xp , Windows Server 2003 has a new feature called Low fragment heap(LFH).
If you enable this when creating heap , this can reduce heap fragmentation.The LFH has a predefines set of memory chunks of different sizes. it called this chunk as buckets , so when we request for a a few bytes , the LFH returns the bucket of smallest size.  

The LFH option can be enable by the API HeapSetInformation. For example it may look like
long HeapFragValue = 2;

HeapSetInformation( GetProcessHeap(),HeapCompatibilityInformation,HeapFragValue,sizeof(HeapFragValue) );

2 indicates the information is about LFH.
This feature is very useful. Otherwise you may need to write your own allocators and handle the memory pool.
When writing allocator we need to think about the page size , number of page faults etc. and certainly it takes some time.   So if you are in hurry try the LFH option. :)

Thursday, November 15, 2007

How to make application Faster C++/C

Following small optimaization can make applications more faster . I think.


1.Make small functions  as inline functions.


2. If you are  using variable to hold constant data , make in const.
like int i = MAX_VAL; can be changed to const int i = MAX_VAL


3.Creating simple expressions
some exmaples like belowif(i == MAX_VAL) return 1;
else return 0 ; 
can be replaced with return ( i==MAX_VAL); 

another one if( i ==0 ) return nVal; else returrn 0; can be replaced with  return (i==0) ?nVal : 10   Ternary operator is fast than if else.
   
4.When function calling don't pass long arrays . Use pointers or reference.

5.For copying array use api , like CopyMEmory , memcpy.
(They uses asm codes to get the tas done)


6. similarly for initializing memset also can be used .


7. When increamenting class objects uses ++obj , rather than obj++. 
(because obj++ might create  temporary objects).


8. Too much object oriented approch will also affect speed.


9. when one function called ,  It is wise to return first if any argument is invalid , rather than do it later.
like
fun()
{
   if(param == 0 || param1 = 0 || n!=V) return 0;
   return 1;
}


10. Allocating memory several times wil cause fragmentation, so allocate a buffer pool first.


11. Similarly try to avoid creating mutiple files in Hard disk .It will also cause fragmentation.
      Try to do the work with one file, otherwise think about databases.

    
12.  Use int , as loop couner etc. Because int size same as the processor register size, so it is fast than others.


13.  Exception catching is expensive , it will cause application slower , and will increase the size of  EXE.


Do if you are not using exception handleres , you can turn it off in compiler settings
Also avoid putting exception handling inside repeatedlycalling functions .
Put exception handling on in the main parts of program.


 14. you can use __fastcall to make functions calls faster , it wil try to put arguments in registers._cdecl will increase the size of EXE.


 15. Don't load all DLLs on application loading . Most of the cases applications slowing down due to these reasons.
 DLL as name implies is for dynamic loading.


16. Most important , Before copying code from somwhere Understand it :)

Monday, October 29, 2007

C,C++ Geek's way to access array/ pointer elements.


After a short gap , i am back. This is post is from old memories. I don't know how many people know this ?
I don't want to explain much. Look the following codes

int nArCounts[3]   = {30,20,50};

Normally people accessing array element like nArCounts[i].

It is also possible to access it like this i[nArcounts] ,Both are converted to nArcounts + i .
Thats all , But if a guy don't know this , when he/she sees these type of notations he will get mad. I am sure. 


Friday, September 21, 2007

STL vector and Some memory concerns.


I know STL vector is smart & very efficient . But when we using it lacks some memory deallocation functions other than destructor.
This is depending according to the version of Visual studio you are using . If you are using VS7 , the vector::clear() will remove all memory used by the vector. Otherwise , i mean if the compiler is VS2005 , you are in trouble. The vector hasn't any functions to release all memory used by it , except ~vector() (destructor).

Consider the following situations using VS2005

vector <int> myVec;
for(int i = 0 ; i < 10000; i++) myVec.push_back(i);
// ....some  codes.......

myVec.erase(myVec.begin()+1,myVec.end()); /*  removed all elements except the first.
                                                                     But memory still allocated , because vector
                                                                     reserved the memory for future allocations.*/

erase will mearly just removes  elements from the vector and calls destructor (->~_ty()). So still the memory is not deallocated(call myVec.capacity() to see the allocated bytes) .. What to do ? if you want to free up memory (Ofcourse u can delete , the last way).
One trick is to copy the contents to a new vector and again recopy it to the original vector , see below. Here the new vector(copy) will takes only the actual memory (it can be verifed using vector::capacity() ). During the recopy to original vector (myVec = copy) , the unwated memory is deleted.

Like

{

    vector<int> copy  = myVec;
    myVec  = copy.

}

So now the memory will be delted.. Ofcourse it makes some perfomance imacpt due to copy operation . But In some cases it can save a lot of memory . It depends upon the type of applcation.


Note : I have checked this only with Visaul Studio 7 , 8's  implementaion of STL.


Thursday, September 20, 2007

GetOpenFileName() And Some Deep crashes..

I think most of all windows programmers are familiar with GetOpenFileName() API (in MFC CFileDialog class).This api popups a open file dialog letting users to select the file they want.
Okay , I am going into the matter.
Try opening notepad.
1. click open from menu , now you can see open file dialog. Navigate to Desktop
2  move the mouse pointer around some file till tool tip visible.
3. Now cancel the dialog (press cancel or ESC)
4. Try to repeat the same thing (make sure again you go to desktop) , you will be awaited with a crash. Notepad disappears.


Interestingly This happens only with Desktop. I don't know why . So you might ask me how it mess up with the GetOpenFileName. Yes it relates , try calling GetOpenFileName in win32 App (not MFC). You can see the same behavior , your application crashes..


This is Bug in windows XP ( Service pack??? , any oher Version ??? ) .. i don't about any other versions.
If you debug the application you can't see any stack trace . This also happens with the GetSaveFileName api also.
For calling GetOpenFileName you need initialize COM , by calling CoInitialize(0) in the first of the program and call CoUnitinialize in the end of the program. Then it should work. The interesting thing is that in MSDN there is no information about this.


If you call like this as show below , still you can expect the crash.
CoInitialize(0);
GetOpenFileName();
CoUnitialize()

I don't know the exact reason . But my guess is that the GetOpenFileName() / SaveFileName() creats 4 threads .Even you close the dialog these thread exists ,  and these threads might call some com calls , after your CoUnitialize() . That may cause some problems. The most important this is that , There is a chance to crash every application ,  that uses GetOpenOpenFile/GetSaveFile dialog (and not initializing COM) . Seriously..

Sunday, August 26, 2007

Type casting using Assembly code win32


We know that C++ will not allows assiging variable if they are on different typee. In That situations type casting is needed..But In some cases we can't use the c++ inbuilt type casting system as well as C style casting also..

 I am taking an exmaple of CreateThread thread proc function.(Beacuse many people uses static functions as the
thread proc for CreateThread.)

 For example if you look the function CreateThread API,the thread proc type is
DWORD WINAPI ThreadProc(void *lParam)
{

}

So this insist you to create some global functions or static functions.

Hence you can't pass your class member functions to CreateThread. So usually people will create some static functions and pass that function to CreateThread.And from inside that static function the appropriate class function is called..

This is fine. But using a littile asm code this can be avoided.
For example CCoffe is your class, and the MakeCoffe function we want to pass to CreateThread.  This can be done as below.

//sample codes
class CCoffe
{
  DWORD MakeCoffe(void *lParam)
  {
     return 0;
  }
}

//Initialization  function.
CCoffe::Init()
{  
   //temp is a function pointer of ThreadProc Type.
   DWORD (WINAPI*temp)(void*lp);
   __asm //Here we can pass any  address  to temp.      
   {


       mov EAX,CCoffe::MakeCoffe
       mov temp,EAX
   }
   //Call CreateThread with temp
   DWORD  out;
   CreateThread(0,0,temp,0,0,&out);
}

The Point is we can pass any address to temp,using asm block.Passing wrong function addresses 
may cause invalid stack structure,Might result in a crash.Hopes next time you will avoid static functions..

Note: I Don't know is this a good practice or not, If you have any opinion please let me know..


Friday, August 24, 2007

NULL pointer and Some thoughts C++


Its me again , now came with a NULL pointer in hand... You may think what so special about NULL pointer , right ? .

it is very special . for example even if multiply two NULL pointers ,you will get a the result as a NULL pointer.. is it interesting ? .. :) I was just joking.. 

I wrote this beacause mostly people checks in destructor something like this

if(p) delete p;

 This is not needed , you can just avoid that checking, because delete NULL , will not cause any probles.
so if you have more pointers in your class to delete , avoid that checking is too good to see.

I think Now it is good to mention about this function  IsBadWritePtr . This function can be used to check
whether one address is good to write. In MFC there is function AfxIsValidAddress which will call this function to check.

The next thing about NULL pointer is that , You can still call member functions with null pointer, Like

CCLemon *p = NULL;

p->Drink() ;

Still this will works . but only one condition , Drink should not access any member variables of class CCLemon , and Drink shouldn't be a virtual function. If Drink is a virtual function result is Bhooommm!!!





Monday, August 20, 2007

Quick way to disable global keys (like ALT + TAB )


Some times it needed to disable the functonality of the global keys like ALT + TAB ,CTRL + ESC . For example when playing some games , pressing ALT + TAB will not cause to switch the tasks. Personaly i don't like this ,but programmers do these ,otherwise they might needed to handle something more..


So if you want to do these , One way is to use Hooks , using SetWindowHookEx api. But there is much simpler way to do this , using hot keys. There is function named RegisterHotKey , this will define a system wide hot key. So the effect is same as Hook.


After defining a hotkey ,when the hotkey is pressed by the user WM_HOTKEY message will be posted to message queue of that window .


So if you want to disable ALT+TAB , install a hotkey using
                                 RegisterHotKey(hwnd,id,MOD_ALT,VK_TAB).


  Done!!!! . Very simple than hooks.you can also handle the WM_HOTKEY message to do your own tasks..


Thursday, August 9, 2007

operator= & Inheritance c++


One interesting thing about operator = is that it can't be inherited.. So even if your base class has operator=  , no use for derived class. For example CString has operator= , but if you derive a class from CString you will not get = operator functionality in your derived class.

But there is a neat trick that will explicitly put this operator= in to the derived class. Here it is

class CString
{
public :
  CString& operator=(char *)
  {
     // some codes
     return *this;
  }
};
class CMyString : public CString
{
public:
  //We explicitly inserted the operator.
   using CString::operator=; 
};

Now CMyString gets the operator from CString.

Wednesday, August 8, 2007

Checking the presence of Virtual table in a class c++

The Last day when i am debugging one program , i saw the __vfptr symbol in VC++ . This represents the the vtable of a class. When you debuging your program try obj1.__vfptr in watch window. It will show the virtual functions of that class.

On that time I thought about writing such a function to check the vtable presence in a class , it is not a bad Idea..

So This post is about checking the whether a class contains virtual function or not. I want to write a function like IsVTablePresent(MYclass) , the function will return true if there is a vtable ,Otherwise false.

I don't know is this type of functins are really useful or not , but i think these are really smart Smile.

 Here is my solution using templates , It is very easy.

template <typename T>
class tDervVir : public T
{
 virtual void VirtualFun(){} //dummy
};


template <typename T>
class tDervNormal : public T
{
 // No virtual functions inside.
};


template <typename T>
class VFinder                  
{
 public :
 int IsVirtualContains() //this is our function
 {


     tDervNormal<T> obj1;
     tDervVir<T>    obj2;
     return sizeof(obj1) == sizeof(obj2);
 }


};

By using the above classes it can be done. For example consider a class CSample as the class for testing.


class CSample
{
   virtual void PoorMan(){}
};



We can check CSample as the following way

VFinder<CSample> tester;
(tester.IsVirtualContains() ? cout << "Virtual present" : cout << "Virtual not present" ;


Thats all for now..

Tuesday, August 7, 2007

Calling class Constructor C++

Some times we may think it would be nice , if we can call the constructor again for some initialization stuff (Normally constructor does the initialization job).  It is not possible to call the constructor of a class explicitly. Only way is to call is new operator. So here is that.

It is achived using placement new technique. it is very easy. For example if you have class CAlgoritham and the constructor of CAlgoritham does most of the initialization works. So after some processing you may want to  reset it to the old state (may be depnds on the algoritham). You have already wrote the initialization codes in constructor , but it is not possible to call constructor again. So we can use placement new. Here it is


CAlgoritham alg; //member variables Initialized already
alg.DoProces113();


new (&alg)CAlgoritham(); //this will call consructor again.But it  will not create a new memory (since we are giving memory location).


The statement new (&alg)CAlgoritham() is equal to CAlgoritham::CAlgoritham();

I like this kinda of things. Hopes you too. 

Saturday, August 4, 2007

STL Vector in VS 2005 ( when porting from 2003 or < )

In VS 2005 they changed almost all C runtime libraries and STL classes for adding security practices. Here is one information about the vector class in STL. So if you have any code written in 2003 , and if you port that to VS2005 be careful. 

In 2003 the following vector operations will work , like
vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);


vector<int>::iterator it = SomeInts.Begin(); // Now it points to 0
++it;                                       // Now it points to 1
SomeInts.erase(it);                         // We are deleting the 1 from list
--it                                        // We want to move to 0 again.


and if you again ++it you will get 2. because we just deleted 1 from the vector. Ok, everything fine.
But In VS 2005 , the red marked line above(--it) cause to a crash!!! Open-mouthed. Because the iterator it is invalid so --it is also invalid.

 SO to correct that error best way is like this

vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);
vector<int>::iterator it = SomeInts.Begin();   // Now it points to 0
++it;                                          // Now it points to 1
it = SomeInts.erase(it);                       // We are deleting the 1 from list
--it                                           // Now it points to 0


[ The last day , my friend told me he is getting a strange error in VS2005 , not in 2003, it was this problem. Smile]

Thursday, August 2, 2007

Calling Destructor & Virtual table c++

IF you really know how virtual functions work,it is really fun. Here is such an example(for fun i wrote a function fun  )

class base
{
public :
   virtual void fun()
   {
        cout <"base fun";
   }
  ~base(){}
};
class deriv: public base
{
    void fun()
    {
         cout << "deriv fun";
    }
   ~ deriv(){}
};

very simple two classes..
We know virtual funtions are initlaized in constructor and removed to their old base versions in the destructor.

Here is One more proof .
Try these if you are interested , otherwise go to www.youtube.com

base *p = new deiv();
p->fun();
p->~base();
p->fun();

the outputs will be first

deriv fun and
base fun

Because when we call p->~base() it will replaces the virtual pointer with the base version of fun. Thats why the base::fun get called.
We can't call constructor explicity as we did with destructor.
 Ok , I am stopping now.




Tuesday, July 31, 2007

RichEdit Common Mistake MFC Win32

 If you ever tried RichEdit control in Vc++ , may be at first use you will notice that your application may crash , or the dialog is not coming.  The problem is , the RichEdit module is not loaded to memory initially. We need to load it explicitly. IF you are using MFC there are functions like
AfxInitRichEdit2(); // RichEdit Version 2
and
AfxInitRichEdit();  // RichEdit version 1.
If you are doing pure win32 , just by loading the richedit2.dll to meory will solve the problems , like
LoadLibrary("c:\\WINDOWS\\system32\\riched20.dll"); // this is richedit version 2.also remember to unload the module with FreeLibrary function.
You need to call the approrpiate function (AfxInitRichEdit or LoadLibrary) before creating richedit. The best way is to call is  in the InitInstance in MFC , or winmain Win32.

Thursday, July 26, 2007

Empty class size c++

People may thinks like the size is zero for an empty class (Me also thought
i
n the beginning). But it is not true. The size of an empty class will be never
zero. It is nonzero. There are two reasons for that.

1) the sizeof operator in c++ never returns zero.
2) IF the size becomes zero it may cause to have some invalid address
arithmetic operations.

so the size of an empty class is never zero , it is always nonzero (and this
value depends on compiler).

Friday, July 6, 2007

Placement New


This is not a new subject. Many of us knows this. Many not knows.
Placement new means we can ask the new operator to allocate from a particular memory area. This can be useful when implementing memory pools , to avoid fragmentation of memory.

This is the way to do this.

// Our mem pool of size 1000 bytes.
unsigend char *pMemPool = new unsigned char [1000]; // 1000 bytes is a sample ,use large numbers here.

Now i can ask new to allocate to pMemPool like this

Someclass *p = new (pMemPool) new Someclass;

When comparing the p and (Someclass *) pMemPool reveals they are equal. Don't free p, it will delete whole memory pool ( pMemPool). So allocate as much possible to this memory pool, later we can delete the whole pool . This helps to avoid memory fragmentation.

Monday, May 7, 2007

Easy way to Disable IME window in an Win32 Application

In this world of Unicode still we often do non Unicode applications. But there is a feature in windows operating system it allows to enter Unicode characters or characters other than basic ascii character set to our application.So What happens is when user press enter key these unicode characters will turn to "????" .Because our application is non Unicode .

So there is a easy way to disappear this IME window when our application comes to front. Microsoft provides api like

1 ImmDisableIme
2 ImmAssociateContext

So if you want to make disappear the ime window for a particular window in you application , you can use ImmAssociateContext.

like ImmAssociateContext(YourHwnd,0) , If don't wan to use the ime feature at all use ImmDisableIme().

The ImmDisableIme will cause to disable IME for all windows in you application .One important thing you should call this function , before any window is created.
Like ImmDisableIme( GetCurrentThreadID()). For an mfc application the best place to call is from CYourApp::InitInstance() , where CYourApp derived from CWinApp.