Category Archives: C/C++

Difference between memmove() and memcpy()

“The memmove() function copies n bytes from memory area src to memory area dest. The memory areas may overlap: copying takes place as though the bytes in src are first copied into a temporary array that does not overlap src or dest, and the bytes are then copied from the temporary array to dest.”

“The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove() if the memory areas do overlap.”

So basically memmove() can handle memory overlapping but memcpy() cannot. Let’s take a look at an example to illustrate this:

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

char str1[7] = "aabbcc";

int main( void )
{
    printf( "The string: %s\n", str1 );
    memcpy( str1 + 2, str1, 4 );
    printf( "New string: %s\n", str1 );

    strcpy( str1, "aabbcc" );   // reset string

    printf( "The string: %s\n", str1 );
    memmove( str1 + 2, str1, 4 );
    printf( "New string: %s\n", str1 );

    /* output:
        The string: aabbcc
        New string: aaaaaa
        The string: aabbcc
        New string: aaaabb
    */
}

Additionally, strcpy() cannot handle the memory overlapping problem too. Also not as described above memmove() do not need temporary space to finish coping. The implementation of memmove() could be like this:

if src > dest; then
    copy src from the beginning
else if src < dest; then
    copy src from the ending
else // src == dest
    do nothing

strcpy() can make use of the similar method to handle memory overlapping or just call memmove().

Virtuality in constructor and destructor in C++

Fact 1: there is no virtual constructor.

Reason: the compile should well know what exactly the type is to be created. Also technically speaking we can not get the dynamic dispatch information (virtual table) which is created only after the object is constructed.

Fact 2: there is virtual destructor.

Reason: it’s quite useful when you want to delete an object of a derived class through pointer to base class. So with out virtual there might be memory leak, since the destructor of derived class won’t be called. Let’s look at an example.

In this code the derived’s destructor is not called, for base’s destructor is not of type virtual.

#include <iostream>

class base
{
   public:
      base(){cout<<"Base constructor"<<endl;}
      ~base(){cout<<"Base destructor"<<endl;}
};

class derived: public base
{
   public:
      derived(){cout<<"Derived constructor"<<endl;}
      ~derived(){cout<<"Derived destructor"<<endl;}
};

int main()
{
   base* p = new derived();
   delete p;
   return 0;
   /* output:
      Base constructor
      Derived constructor
      Base destructor
   */ 
}

Now we specify the type of base’s destructor as virtual, then the derived’s destructor is called

class base
{
   public:
      base(){cout<<"Base constructor"<<endl;}
      virtual ~base(){cout<<"Base destructor"<<endl;}
};
...

int main()
{
...
   /* output:
      Base constructor
      Derived constructor
      Derived destructor
      Base destructor
   */ 

}

Fact 3: Never use virtual function member inside the constructor or destructor.

Reason: Assuming the virtual function is called in base constructor, when we declare an derived object, the base constructor would be called first. Then the virtual function in base would be called instead of going down to find a derived implementation of the virtual function, because the derived member hasn’t even been constructed at this moment. Same reason for destructor.

Let’s look at an example: Even the type of object a is derived, the foo() in base is called anyway.

#include <iostream>

class base
{
   public:
      base(){foo();}
      virtual void foo(){cout<<"base vfunc"<<endl;}
};      

class derived: public base
{
   public:
      void foo(){cout<<"derived vfunc"<<endl;}
};

int main()
{
   derived a;
   return 0;
   /* output:
      base vfunc
   */
}

Above code’s logic is wrong but would be compiled well, but if we use pure virtual function, then error would be throw out, which can explicitly prove what we discussed above

<pre>
class base
{
   public:
      base(){foo();}
      virtual void foo()=0;
};
...

int main()
{
...
    //compile error: abstract virtual `void base::foo()'
    //called from constructor
}

Private virtual function member

Fact 1: the private virtual function member of base class can be overridden by derived class. we can prove this by defining a private pure virtual member, the compiler will give error that force you to override it:

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

class base
{
   private:
      virtual void vfunc() =0;
};

class derived:public base
{

};

void main() 
{  
   derived a; //error " cannot declare variable 'a' 
              //to be of type 'derived'"
              //since the following virtual functions 
              //void base::vfunc()are abstract:
}   

Fact 2: If the private virtual function member is not overridden by derived class, the derived class cannot call it directly. However, we can define a public or protected function member in base class to call the base class’ private virtual function member. So that we can use derived class to call the private virtual member, since the public or protected function member is inherited by derived class and can be called by derived class. Let’s see a snippet. It’s quiet simple:

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

class base
{
   public:
      void call_private_vfunc()
      {
         vfunc();//or: this->vfunc();
      }
   private:
      virtual void vfunc()
      {
         printf("I am virtual func of base class");

      }
};

class derived:public base
{

};

void main() 
{  
   derived a;
   a.call_private_vfunc();
   //it will print:
   //"I am virtual func of base class"
}

Difference between a and &a

code

#include <stdio.h>
void main(void)
{
    int a[5]={1,2,3,4,5};
    int *ptr=(int *)(&a+1);
    printf("%d,%d",*(a+1),*(ptr-1));
    return;
}

output:

2, 5

Analysis:

a: the array (type is int[5]) or the address of the first element of array (type is int*)
&a:  pointer to the array (type is int (*)[5])
&a[0] : the address of the first element of array (type is int*)

sizeof(a) = sizeof(int[5]) = 20
sizeof(&a) = sizeof(int(*)[5]) = 4

*(ptr-1)=*((int*)(&a+1)-sizeof(int*)) = *((int*)(&a+sizeof(a))-4) = *((int*)(&a+20)-4) = *(&a[5]-4) = a[4] = 5

*(a+1)=*(&a[0]+sizeof(int*))=*(&a[1])=a[1] = 2

Macro vs Inline

Macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.

#define BUFFER_SIZE 1024
foo = (char *) malloc (BUFFER_SIZE);
// ==> foo = (char *) malloc (1024);
#define min(X, Y)  ((X) < (Y) ? (X) : (Y))
x = min(a, b);
// ==> x = ((a) < (b) ? (a) : (b));

Inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined.

inline int max(int a, int b)
{
  return (a > b) ? a : b;
}
a = max(x, y); // ==>; a = (x > y) ? x : y;

Benefits of Inline(from wiki)

Traditionally, in languages such as C, inline expansion was accomplished at the source level using parameterized macros. Use of true inline functions, as are available in C99, provides several benefits over this approach:

  • In C, macro invocations do not perform type checking, or even check that arguments are well-formed, whereas function calls usually do.
  • In C, a macro cannot use the return keyword with the same meaning as a function would do (it would make the function that asked the expansion terminate, rather than the macro). In other words, a macro cannot return anything which is not the result of the last expression invoked inside it.
  • Since C macros use mere textual substitution, this may result in unintended side-effects and inefficiency due to re-evaluation of arguments and order of operations.
  • Compiler errors within macros are often difficult to understand, because they refer to the expanded code, rather than the code the programmer typed. Thus, debugging information for inlined code is usually more helpful than that of macro-expanded code.
  • Many constructs are awkward or impossible to express using macros, or use a significantly different syntax. Inline functions use the same syntax as ordinary functions, and can be inlined and un-inlined at will with ease.
  • Many compilers can also inline expand some recursive functions; recursive macros are typically illegal.

Switch in loop

When switch is used in a loop, we should know the different effects of following case:

1. break;     //code would jump to the first statement after the switch block
2. continue; //code would jump to the next loop
3. do nothing;   //code would continue to the next statement(next case)

Let’s illustrate this by looking at an example:

#include <iostream>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[])
{
    int number;
    while( cin >> number )
    {
        switch(number)
        {
            case 1:
                cout << "u input 1 and break" << endl;
                break;
            case 2:
                cout << "u input 2 and continue" << endl;
                continue;
            case 3:
                cout << "u input 3 and do nothing"<< endl;
            default:
                cout << "default..." << endl;
                break;
        }
        cout << "after switch number: " << number << endl;
    }

  system("PAUSE");
  return 0;
}

output:

----Hit any key to start.
1
u input 1 and break
after switch number: 1
2
u input 2 and continue
3
u input 3 and do nothing
default...
after switch number: 3
4
default...
after switch number: 4