Saturday, April 21, 2012

Atbroker.exe application error in Win7

Last weekend I tried to access my office machine using remote desktop from my home, I got this popup window with the error message "The Application is failed to initialze properly. Click OK to terminate the application". Snapshot is given below.

When you click on OK button, you will recieve blank screen.


Initially I surprised to see this message and unable to login to my office machine. later I did gooogling and found simple work around for this by just clicking CTR+ALT+END.

Tuesday, April 17, 2012

Register storage class in C!!

Register storage class is used to store the local variable in the CPU memory. This is similar to auto variable except storing the data in CPU memory instead of main memory. So there wont be any address for the register variables, because it stores in CPU memory called registers.  As there are only limited registers in the CPU, There is no guarantee that all register variables are stores in CPU memory. If CPU memory is full (no register variables available), it stores in main memory. We are only intimating to the compiler as a register variable. It completely depends on the compiler whether to store in CPU memory or main memory. So its better to declare register variables only if needed. Accessing register variable is very quick and efficient.
  • Keyword : register
  • Default value : Garbage value
  • Memory Location : CPU memory (Registers)
  • Scope : Local to the block or function
  • Lifetime : till CPU memory resets or end of the application/program 

 Sample Code for Register storage Class:
main()
{
    register r = 20;
    printf("r value is %d\n",r);
    //printf("r address is %d\n",&r); // can't access address of the register variable
}

Output:
r value is 20

Output : When try to access the address of the register variable, got the following error
reg.c: In function 'main':
reg.c:6: error: address of register variable 'r' requested

 Accessing the address of the register variable is illegal as it doesn't have any address. So '&' unary operation fails on register storage class. Register can be used for the variables which can be used frequently like counters  and need quick access.

Monday, April 16, 2012

Extern storage class in C!!!

External storage class is used to give the reference for the global variable which is visible to the whole application/program. When you declare variable as extern, variable can't be initialised, its only a declaration. Memory will not be allocated to the extern variable. But it will point to the variable which is already declared somewhere in other file. Extern is the default for all global variables and functions.
  • Keyword: extern
  • Default value: zero if not initialised .
  • Memory Location: Main memory
  • Scope: Global to the whole program/application
  • Lifetime: Global to the whole program/application

Sample code for Extern storage class:

// file name is file1.c and code is below

static int i=10; // i is static, so its scope is limited to this file only
main()
{
    print();
}

// file name is file2.c  and code is below

#include 
extern int i; // i is extern, so i value is somewhere in ohter file 
extern void print();
void print()
{
    printf("i is %d\n",i); // will get error here, because in file1.c i is static
}

Output :
i is 10


When you have multiple files, and you declared a global variable in on file and you want to use the same varaibel in other file, you need to declare the variable as extern in other file. Just for understanding and letting to know the developer, we are using extern. By default global variables are extern, if you not declare as extern, compiler by default assumes all global variable are extern variables.

Friday, April 13, 2012

Static storage class in C

Static  storage class will be used when the value of the variable should be persistent between the function calls. default value for the static variable is zero. And scope of the variable or function is limited to the file only.

  • Keyword: static
  • Default value: zero if not initialised .
  • Memory Location: Main memory
  • Scope:  Local to the function or block
  • Lifetime:  till the program or application completes
Sample code for static storage class:
int test()
{
    int a=10; // local to test() function
    printf("a value is %d\n",a);
    a++;
}
int static_test()
{
    static  int st=10; // stativ variable, value will be restored
    printf("st value is %d\n",st);
    st++;
}
main()
{
    printf("************************** non-static value **********************************\n");
    test();
    test();
    test();
    printf("************************** static value **********************************\n");
    static_test();
    static_test();
    static_test();

}

Output:
**************** non-static value **********************************
a value is 10
a value is 10
a value is 10
************************** static value **********************************
st value is 10
st value is 11
st value is 12

From the above sample code, it is clear that static variable in static_test()  function is restoring the value by incrementing one, where as in test() function value is always same.


Static Initialization:  Static variable initialises only one time in whole program. And it restores the new value when changes. See the sample code below.

main()
{
    for(int j=0;j<5;j++)
    {
        static int i=10; // this executes only once, it wont execute for each iteration
        printf("i is %d\n",i++);
    }
}

Output:
i is 10
i is 11
i is 12
i is 13
i is 14

In the above sample code, static integer variable initialised in for loop. Because of static property, it wont initialise for each iteration. for auto variables it will initialise for each iteration.

Scope Limitation: Scope of the variable is limited to the file if you declare it as static. see the sample code below.
// file name is file1.c and code is below

static int i=10; // i is static, so its scope is limited to this file only
main()
{
    print();
}

// file name is file2.c  and code is below

#include 
extern int i; // i is extern, so i value is somewhere in ohter file 
extern void print();
void print()
{
    printf("i is %d\n",i); // will get error here, because in file1.c i is static
}

Output with static:
/tmp/ccwXbAno.o: In function `print':
file2.c:(.text+0x6): undefined reference to `i'

Output without static:
i is 10

 In the above code, there are two files file1.c and file2.c. static variable i is declared and initialised in file1.c, and trying to access in file2,c in print function. at this time we will get the error, because of declaring i in file1.c as static.  if the variable is not static we will get the output shown above.

P.S:  Static keyword behaviour varies in C++. Click here for static behaviour in C++.

Thursday, April 12, 2012

Auto storage class in C!!

Auto is the default storage class for the local varaibles.  Auto is a short form for Automatic.

  • Keyword :  auto
  • Default value : Garbage value
  • Memory Location : Main memory
  • Scope : Local to the block or function
  • Lifetime  : Till the application runs or until memory location destroys 
Default value sample code:

int main()
{
    auto int a;
    int i;
    printf("a is %x\ni is %d\n",a,i);
}

OutPut:
a is 0
i is 0

In the above code, two integer variables are declared as automatic , in that one is using keyword and another one is without keyword. both variables behaviour is same. They are not inittialised, so default value is garbage value. Here in the output , it  is zero. Defualt value is depends on the machine. I am using Unix, so got default value zero. If you use Windows , you may get garbage value. So if you not initialise the variable, result is undefined. So its always better to initialise the variables.

Variable initialization:

int main()
{
    auto int a=20;
    int i=20;
    printf("a is %x\ni is %d\n",a,i);
}

OutPut:
a is 20
i is 20

In the above code, two integer variables are declared as automatic , in that one is using keyword and another one is without keyword. both variables behaviour is same.

Scope or visibility sample code:

int main()
{
    auto int a=20;
    {
        int a = 30; // scope is limited to this block
        int i=20; // scope is limited to this block
        printf("a is %d\ni is %d\n",a,i);
    }
    // we cant access i here
    // a is first declared variable and not the second declared variable
    printf("a is %d\n",a);  
}

OutPut:
a is 30
i is 20
a is 20

In the above code, on integer varibale a is declared in a main block, another two variabels a and i declared in the separted block. second variable a and i are limited to this block only. If second variable is not declared in the block, first declared a variable scope comes to this block also.




Wednesday, April 11, 2012

Storage classes in C

The C programming language supports  a feature called storage class which defines the scope or visibility, life time and memory location of the variable/functions. There are four types of storage classes in C namely
Lets see what is scope and life time of the variables.

Scope or Visibility: Scope means accessibility of the variable. i.e till which part of the code, we can access the variable. for example, if you declare  the variable with in the braces, scope is limited to that block only. Generally variables scope is limited to within the function only. See the sample code below.
main()
{
    int a;
    {
        int b;
        {
            int c;

        }//scope of the variable 'c' ends here

     // cant access variable 'c'

    }//scope of variable 'b' ends here
}

There are four types of scopes in C which are given below.

Block scope: scope of the variable is limited to block. we cant access that variable outside the block. Block of the code is area between the two curly braces as shown in the above sample code.
Function Scope: Scope of the variable is limited to the function. This is the default scope for all the local variables.
File scope: Scope of the variable limited to file. We cant access the variable outside the file. We can limit the variable scope to the file using static storage class.
Application scope: Application scope or program scope of the variable is visible to whole application. This will be implemented by using extern storage class.

Life time of the variable: Life time of the variable is to check whether variable available  in the memory or not. If available , till which portion of the code,  variable is available in the memory without destroying. Even though scope is limited to the block or fucntion , lifetime of that varible available until it destroys in the memory. For each varaible until it is available in the memory, it is having the scope or visibilty. If variable is not available in the memory,  there wont be any scope for that variable.
void lifetime_variable()
{
    // x scope is within this function and life time is whole program becaus of static
    static int x=0; 
    x++;
    printf("x value is %d\n",x);

}
main()
{
   lifetime_variable();
   lifetime_variable();
   lifetime_variable();
}

Output:
x value is 1
x value is 2
x value is 3

In the above sample code, in the function lifetime_variable() variable x  scope is limited to that function only. But life time is through out the program. It wont destroys until program detroys. 

Monday, April 9, 2012

Relation between pointers and arrays in C

In Programming langauge C, there is a strong relation between pointers and Arrays. Lets see them in detail. starting fromt the definition.

Array: Is a sequence of memory to store the similar data type. Using index or position, we can access the data from array.
Pointer: is a variable pointing to some memory location. Using this we can access the memory directly.

Most people think that, pointers and arrays are same. but its not true. Some times they are equivalant depending on the context and ussage.  Indexing and pointer arithamatic works on both pointers and arrays. So these are same for both. See the below sample code.

#include
main()
{
    char arr[]="hello";
    char *ptr = arr;
    printf("%c %c \n",arr[3],ptr[3]);
    printf("%c %c \n",*(arr+4),*(ptr+4));
}

Output:
l l
o o

From the above code, accessing the content using indexing is legal for both pointers and arrays. In that code starting address of the array is assigined to a pointer. So both pointing to the same address.


Graphical represetation Of memory using array and pointer:
Memory represetaion of array and pointer

From the above image, it is clear that array stars from the index zero, where as pointer stores the address of the first index in the array.

Pointer Arithmatic: It is legal  to perform arithamtic add/subtraction on pointer variables. Lets compare array with pointer for this with example.

char arry[]="hello";
char *ptr;
ptr=&arry[0];


From the abvoe code snippet,  adrress of the arry index zero is assinged to ptr. Now both ptr and arry[0] are pointing to the same element.  Its perfectly legal to access the next element from ptr location using statement  *(ptr+1). ptr+1 points to the next elemnt of the ptr and * indicates access the value. Similarly ptr-1 points to the previous element from the ptr. Like this array index also works similarly. zeroth element is *(arry+0)  and 1st element is *(arry+1) and nth element is *(arry+n). Using mathematics assosiate law we can write (arry+a) as (1+arry). So its legal to access the 1st element using 1[arry] statement.
There is one basic difference between array and pointers. Pointer is a variable. So below statements are true for pointer.
ptr=arry; // assinging array to the ptr
ptr++; // incrementing the ptr, which points to the next element after increment.
But array is not a variable , so these operations are invalid.
arry=ptr; //illegal
arry++; // illegal, because arry is contant pointer,

Passing as arguments: Arrays passed to the functions converted to pointers. see the sample code below.

void arry_ptr(char arr_arg[],char *ptr_arg) // one is as n array n other is a pointer
{
    char a = arr_arg[4];
    char b = ptr_arg[4];
    printf("a is %c\n",a);
    printf("b is %c\n",b);

}
main()
{
    char arr[]="hello";
    char *ptr;
    char *ptr1;
    char *ptr2;
    ptr=&arr[0];
    arry_ptr(arr,ptr); // passing arr n ptr as arguments
}


OutPut:
a is o
b is o

In the above code, we passed arr and ptr  passed as a function arguments and accessed the same position element in the function. we got same output for both array and pointer. So when passing array as a function arg, compiler will convert it into pointer.

Wednesday, April 4, 2012

What is big-endian and little-endian?

Endian ness is used to specify the order in which a sequence of bytes (not bits) are stored in a computer memory. There are two types of endianness namely big-endian and little-endian. Big-endian is an order in which most significant byte(MSB) is stored first. Littl-endian is an order in which least significant byte(LSB) is stored first. For example two byte hexadecimal code 4F5E will be stored as 4F5E in big-endian. In little endian systems it will be stored as 5E4F. Lets more clearly.

Generally memory is a collection of bytes. Each byte is collection of eight bits. So data will be stored in the memory byte by byte. This storage criteria depends on the machine architecture. But bits with in the byte is always same. Even though data storage in the memory is depends on the machin architecture, there should be some common point to uderstand and to communicate with other machines. below is the one

  • A bit has a value (on or off , zero or one )
  • A byte is sequence of eight bits
    • the left most bit in the byte is biggest. So the binary value 00001011 decimal value is 11 (8+2+1 = 11).  
    • Bits are numbered from right to left.  Bit zero is the right most and smallest. Bit seven is left most and largest.
So above are the common in all machines. Storing data in the byte is common in all machines. If you are manipulating the memory with one byte data (like char in C). There wont be any problem. Because storage process for bits in byte is common to all machines. But if are manipulating the data with multiple bytes (like int, float in C), there comes the problem. Lets see the byte ordering and storage.

Byte ordering:
Assume that there are sequnce of 4 bytes namely W, X, Y, Z. And their corresponding values are given in the given table in hexadecimal. i.e byte W address is zero and value is 0x12 in hexa (00010010 in binary). similarly for other bytes X,Y, Z are shown below.

Byte Name:    W       X       Y       Z
Location:     0       1       2       3
Value (hex):  0x12    0x34    0x56    0x78

Assume that there is a two byte XY, its corresponding value si 3456 in hexadecimal. So reading this data in both endians in the following way.
Big-endian: stores data big-end first. So it starts reading from big-end, here it is X as a first byte and its value is 0x34 and Y as  second byte and its value is 0x56.
Little-endian: stores data little-end first. So it starts reading from little-end, here it is Y as a first byte and its value is 0x56 and X as a second bytes and its value is 0x34.

IBM's 370 mainframes, most RISC-based computers, and Motorola microprocessors use the big-endian approach. TCP/IP also uses the big-endian approach. So big-endian is also called network order.On the other hand, Intel processors (CPUs) and DEC Alphas little-endian.


Samplec code to find the endianness of the machin in C:
main()
{
    int i=1;
    //typecasting int to char to read the first byte value
    if(*(char *)&i == 1)
        printf("Little endian\n");
    else
        printf("Big endian\n");
}

OutPut:
Little endian

In the above code,  initialised the int variable i with value one. In C generally memory required to store int is either 2 or 4 bytes. Here in our machine it was 4 bytes. In the if statement , we tried to read the first byte by typecasting it to char * (as char need only one byte to store) and checking that value with assigned value. If it is little endian least byte would be value one, if it is big endian most significant byte value would be one.

Tuesday, April 3, 2012

what is virtual table or Vtable in C++?

In C++ for implementing virtual functions, compiler uses Virtual table or simply Vtable. This is also called virtual function table or virtual method table.  Lets see what is it and how it works.

As you know virtual functions are used for run time binding or function overriding. If a class contains a virtual function, you will get one virtual table for that class. This applies for derived classes also. So for each class which contains atleast one virtual function, we will be having corresponding Vtable. Compiler create this Vtable at the time of compilation. Vtable is a static array which contians one entry for each virtual fucntion that can be called by object. Each entry in the Vtable is a function pointer to the "most derived" function.

The compiler will also add hidden pointer called *_vptr to the Vtable for the base class. *_vptr will be inherited to the derived class Vtable also. *_vptr pointer adds to the Vtable automatically when instance is creatd. See the below sample code snippet and  image for more clarity.

class vtBase
{
    public:
        virtual void display()
        {
            cout<<"this is dispaly function"<<endl;
        }
        virtual void displayMore()
        {
            cout<<"this is dispalyMore function"<<endl;
        }

};

class derivedD:public vtBase
{
    public:
        void display() // display function overriding
        {
            cout<<"this is derived display function"<<endl;
        }
};
class derivedDD:public vtBase
{
    public:
        void displayMore() //displayMore function overriding
        {
            cout<<"this is derived displayMore function"<<endl;
        }
};


In the above code there is base claass vtBase with two virtual functions display() and displayMore(). There are two derived classes in which derivedD is override the function display() with new definition and derivedDD is overrdes the definition for displayMore().  The corresponding Vtable is given below.

Virtual Table
In the above Vtable, base class *_vptr is pointing to the base class vtBase table and its member functions are function pointers to the base class.  And derived class *_vptr are pointing to the derived calls Vtable pointer. And in derived class derivedD , you will have two member functions derived from base class, in that one member function display() is overrides with new definition. So its "pointer pointing to the derived member" function and displayMore function "pointer points to the base class" pointer. Similarly for the derived classe derivedDD, but here displayMore()  is overrides with new definition. So this function pointer points to derived class and display()  function pointer points to the base class.

what happens when object creation:

main()
{
    derivedD D; // creating derived object
    vtBase *bPtr=&D; // assining to base pointer
    bPtr->display();
}

Output:
this is derived display function

In the above main fucntion,  in line no. 5,  by seeing this, compiler finds display()  is virtual function, and then it gets vPtr->display() value as derivedD virtual table from there it looks for the display() function pointer. all this happens in three steps
  • finding function as virtual
  • calling _vptr for getting Vtable address
  • finding the pointer for the function

 Using this Vtable process the compiler resolves to the proper virtual function even if you use pointers and references. You can also access the Vtable pointer by using _vptr. see the sample code snippet below.
main()
{
    derivedD D; // creating derived object
    vtBase b; // creating base object
    vtBase *bPtr=&D; // assining to base pointer
    bPtr->display();
    cout<<"_vptr is "<<bPtr->_vptr<<endl; //accessing the _vptr
    bPtr=&b; // assining to base pointer
    bPtr->display();
    cout<<"_vptr is "<<bPtr->_vptr<<endl;//accessing the _vptr
}

Output:
this is derived display function
_vptr is 0x400cb0
this is dispaly function
_vptr is 0x400d30


Monday, April 2, 2012

What is the difference between malloc and new?

This is the regular question generally you will get in C++ Interviews. Both new and malloc are used to allocate the dynamic memory. malloc is used in C and new is used in C++. And the basci difference is new calls the constructor to allocate the memory whereas malloc() is itself is a function and it wont call the  constructor. Lets see the differences.

malloc:
  • This is a function
  • It will return the void pointer.
  • Need to type cast to the required data type.
  • It returns NULL if there is no enough memory.
  • It works in C and C++
  • need to use free to deallocate the memory
  • This cann't be overleaded
  • syntax:
               void *malloc(size_t size)

  • example:
  • int *ptr;
    ptr = (int *)malloc(10*sizeof(int));  // allocationg 10 bytes of int type
    //do something
    free(ptr); // deallocating the memory
    

new:
  • new is an operator.
  • It calls the constructor while allocating the memory and destructor while deallocating the memory
  • It will return required pointer data type
  • No need to type cast
  • It will return bad exception when there is no enough memory
  • It works only in C++
  • Need to use delete for deallocating the memory
  • its possible to overload the new operator
  • Syntax:
            ptr = new typename; 
where ptr is pointer of typename(generally class name).
  • example:
  • int *p;
    p = new int; // allocating int datatype
    //do something
    delete p; // for deallocating the memory
    


Popular Posts