Common GDB Debugging Question

How to attach gdb with running process

Remote Debugging using gdb

How to debug multi threaded application using gdb

Advance debugging C/C++ code in GDB in Linux

You may also like:

  Singleton Design Pattern example in C++


 

CMakeLists.txt and cmake interview questions

 

 

How to attach gdb with running process

How to attach gdb with running process ?
gdb <PROCESS NAME> <PROCESS ID>
 we can grab the process id with ps command.
Suppose your program name is a.out
so command to get the process id would be?
ps -elf | grep a.out
usr1   4473  3529  0 16:42 pts/0    00:00:00 grep --color=auto a.out
here process name is a.out and process id is 4473
so command to attach the running process a.out with process id a.out would be
gdb a.out 4473
Note: You might require to execute as sudo user.

You may also like:

Remote Debugging using gdb

Q) How to do Remote Debugging using gdb?
1) On host machine Start a gdbserver and 2) Connect gdb from Host Machine to remote gdbserver
1) Start a gdbserver:
On Host Machine start gdbserver with application to debug on a specified IP and Port i.e.
gdbserver <IP>:<PORT> <APPLICATION>
e.g.
gdbserver 192.168.1.8:8082 Debug/Dummy
Output:
Process Debug/Dummy created; pid = 3523
Listening on port 8082
It will start the gdbserver for application “Dummy” on port 8082 and will wait for a host to connect to this on port 8082.

2.) Connect gdb from Host Machine to remote gdbserver

From the Host Machine start gdb and execute following command on gdb command prompt
target remote <TARGET MACHINE IP>:<GDBSERVER PORT>
eg
(gdb) target remote 192.168.1.8:8082
It will connect this gdb from Host Machine to remote gdbserver running on Target Machine. Now on Host Machine it will show a gdb command prompt.
output:
Remote debugging using 192.168.1.8:8082
warning: Could not load vsyscall page because no executable was specified
try using the "file" command first.
0x00007ffff7dd9cd0 in ?? ()
(gdb)
Now gdb from Host Machine is connected to target Machine’s gdbserver. Press “c” to continue debugging,
(gdb) c

CMakeLists.txt and cmake interview questions

How to debug multi threaded application using gdb

Q) How to debug a multi threaded application?
NOTE: "ulimit -c unlimited" command to set unlimited size for large core dump generation.
NOTE: "g++ thread1.cpp -g -lpthread" command to compile thread1.cpp file with pthread library.
NOTE: "break funcion_name or filename:line", "run","continue","step","list","print","attach -c core appNmae","bt", "thread apply all bt", "info thread", "thread thread id","bt","quit".
NOTE: step executes a function as a single instruction and continue stepinto the function definition of function.
Command to debug a core file core:
attach the core file and application that has dump the code and take the bt.
"gdb -c core ./a.out"

Then it will show function causing the core dump was called by which thread by seeing start_thread(arg=0xb6bedb40).
Here 0xb6bedb40 is the thread id.

Then run the commands: "info thread" to see the culprit thread "0xb6bedb40"'s stack id.
In this case culprit thread is "0xb6bedb40",whose thread stack id is 3.
So either we can switch to third thread by command "thread 3", and take bt of the third thread only by command "bt" or
we can take stack of all the threads by "thread apply all bt". and use the stack of the thread 3 only to debug or
In this case line at thread1.cpp:37 caused the crashed by thread 3 so we can take bt of "thread 3"
Detailed steps:
-----------------
(gdb) bt //STEP:1
#0  0x08048b3c in odd (o=0x0) at thread1.cpp:37
#1  0xb76f3f70 in start_thread (arg=0xb6bedb40) at pthread_create.c:312
#2  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129
(gdb) info thread //STEP:2
  Id   Target Id         Frame
  3    Thread 0xb73eeb40 (LWP 15708) 0xb7723424 in __kernel_vsyscall ()
  2    Thread 0xb73f0700 (LWP 15707) 0xb7723424 in __kernel_vsyscall ()
* 1    Thread 0xb6bedb40 (LWP 15709) 0x08048b3c in odd (o=0x0) at thread1.cpp:37
(gdb) thread 3 //STEP:4
[Switching to thread 3 (Thread 0xb73eeb40 (LWP 15708))]
#0  0xb7723424 in __kernel_vsyscall ()
(gdb) bt //STEP:5
#0  0xb7723424 in __kernel_vsyscall ()
#1  0xb76f7d4b in pthread_cond_wait@@GLIBC_2.3.2 () at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/pthread_cond_wait.S:187
#2  0x08048a3b in even (v=0x0) at thread1.cpp:17
#3  0xb76f3f70 in start_thread (arg=0xb73eeb40) at pthread_create.c:312
#4  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129
(gdb) thread apply all bt //STEP:5

Thread 3 (Thread 0xb73eeb40 (LWP 15708)):
#0  0xb7723424 in __kernel_vsyscall ()
#1  0xb76f7d4b in pthread_cond_wait@@GLIBC_2.3.2 () at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/pthread_cond_wait.S:187
#2  0x08048a3b in even (v=0x0) at thread1.cpp:17
#3  0xb76f3f70 in start_thread (arg=0xb73eeb40) at pthread_create.c:312
#4  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129

Thread 2 (Thread 0xb73f0700 (LWP 15707)):
#0  0xb7723424 in __kernel_vsyscall ()
#1  0xb76f5178 in pthread_join (threadid=3074353984, thread_return=0x0) at pthread_join.c:92
#2  0x08048c51 in main () at thread1.cpp:54

Thread 1 (Thread 0xb6bedb40 (LWP 15709)):
#0  0x08048b3c in odd (o=0x0) at thread1.cpp:37
#1  0xb76f3f70 in start_thread (arg=0xb6bedb40) at pthread_create.c:312
#2  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129



Q) How to skip 20 lines and show next 10 lines:
list +20,+10

if list shows lines upto 52 then list +20,+10
will displays 10 lines after the line from 72(52+20).
ie it display line 72 to 82

Q) Program using two threads to print odd and even. In each thread function I have knowngly introduced dived by zero error. Need to debug which thread is causing the divide by zero error first and dump core and optimize the code for that thread accordingly.
//Improved Example synchronized using mutex and conditional variable.
#include<iostream>
using namespace std;
#include<stdio.h>
int count=0;
int maxx=10;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* even(void *v)
{
    //cout<<"even thread"<<endl;
    while(count<maxx)
    {
        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)!=0)
        {
            pthread_cond_wait(&cond,&mutex);//wait until count becomes odd
            //it releases the mutex and it waits till condition cond is signaled as complete and mutex is available.
        }
    if(count==6){printf("%d",count/0);}
        cout<<"even "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);//signal to another thread
    }
    pthread_exit(0);//pthread_exit is called from the thread itself to terminate its execution (and return a result) early.
}
void* odd(void *o)
{
    while(count<maxx)
    {

        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)!=1)
        {
            pthread_cond_wait(&cond,&mutex);//wait until count becomes odd
        }
    if(count==5){printf("%d",count/0);}
        cout<<"odd "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);//signal to another thread
    }
    pthread_exit(0);
}
int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_mutex_init(&mutex, 0);
    pthread_cond_init(&cond, 0);

    pthread_create(&t1,NULL,&even,NULL);
    pthread_create(&t2,NULL,&odd,NULL);
    pthread_join(t1,0);
    pthread_join(t2,0);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    //pthread_join is called from another thread to wait for a thread to terminate and obtain its return value
    cout<<endl;
    return 0;
}
-----------------------------------------------
Q) Ho to debug multi-threading Applications with gdb debugger?
Compiling Multi-threaded Code using g++ with Debug Info
g++ -g --std=c++11 -pthread sample.cpp -o sample

Q)How to List all active threads?
“info threads”

Q)How to Check Stack trace of threads ?
In non multi threading applications there is only one thread i.e. main function. Therefore, to check the stacktrace we use command “bt”.
But in multi threading applications, as there are many threads and each threads has its own stack.
But “bt” command will display the stack trace of current active thread only. Now what if want to inspect stacktrace of all the threads at same point ?
To display the stack trace of all the threads use following command
(gdb) thread apply all bt

//output would be

Thread 3 (Thread 0xb74a8b40 (LWP 4335)):

#0  __GI___nptl_death_event () at events.c:31
#1  0xb7faf104 in start_thread (arg=0xb74a8b40) at pthread_create.c:363
#2  0xb7dfc70e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129

Thread 1 (Thread 0xb7cab700 (LWP 4330)):

#0  main () at threadOddEven.cpp:17
(gdb)


Q) How to Switch between threads while debugging?
(gdb) thread <Thread Number>
(gdb) thread 2
(gdb) thread 1

CMakeLists.txt and cmake interview questions

C program to find frequency of each character in a string

//C/Cpp/C++ program to find frequency of each characters in a string
//C/Cpp/C++ program to find non repeating characters in a string
//C/Cpp/C++ program to find repeating characters in a string
//C/Cpp/C++ program to output a1b2c3d4 when input is "abbcccdddd"
/*Idea is to keep count of each characters
'a'=count[0] occurs how many times 0,1,2.3..
'b'=count[1] occurs how many times 0,1,2,3..
.
.
'z'=count[25] occurs how many times 0,1,2,3....
*/
#include<iostream>
using namespace std;
#include<stdio.h>
#include<string.h>
int main()
{
char a='a';
cout<<"a-97="<<a-97<<endl;//0
cout<<"'a'-97="<<'a'-97<<endl;//0

cout<<"manin()\n";
char arr[]="abbccc";
int count[26];
int i;
for(i=0;i<26;i++)
count[i]=0;

i=0;
//while(arr[i]!='\0')
for(i=0;i<strlen(arr);i++)
{
printf("arr[i]=%c arr[i]-97=%d count[arr[i]-97]]=%d\n",arr[i],arr[i]-97,count[arr[i]-97]);
if(arr[i]>='a' && arr[i]<='z')
    count[arr[i]-97]=count[arr[i]-97]+1;//count[arr[i]-97]++;
if(arr[i]>='A' && arr[i]<='Z')
    count[arr[i]-65]=count[arr[i]-65]+1;//count[arr[i]-65]++;
//i++;
}

printf("\nPrinting frequency of each character:\n");
for(i=0;i<25;i++)
{
if(count[i]>0)//characters which occurs atleast once
printf(" %c%d",i+97,count[i]);//a1b2c3
}
printf("\nPrinting repeated character:\n");
for(i=0;i<25;i++)
{
if(count[i]>1)//characters which occurs atleast 2
printf(" %c%d",i+97,count[i]);//a1b2c3
}
printf("\nPrinting character which are unique or none repeating characters:\n");
for(i=0;i<25;i++)
{
if(count[i]==1)//characters which occurs only once or uniquely
printf(" %c%d",i+97,count[i]);//a1b2c3
}


printf("\n");
return 0;
}
/*
a-97=0
'a'-97=0
manin()
arr[i]=a arr[i]-97=0 count[arr[i]-97]]=0
arr[i]=b arr[i]-97=1 count[arr[i]-97]]=0
arr[i]=b arr[i]-97=1 count[arr[i]-97]]=1
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=0
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=1
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=2

Printing frequency of each character:
a1 b2 c3
Printing repeated character:
b2 c3
Printing character which are unique or none repeating characters:
a1
http://www.codeforwin.in/2015/04/c-program-to-calculate-the-frequency-of-each-character-in-a-line.html
*/

C program to convert Decimal to binary, binary to decimal, reverse a number, pallindrom check

Decimal to Binary
//C program to convert decimal to binary
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a decimal number:";//13
cin>>num;
int n,r,i=1;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%2;//13%2=1 //6%2=0 //3%2=1 //1%2=1//
n=n/2;//13/2=6 //6/2=3 //3/2=1 //1/2=0
s=s+r*i;//0+1*1=1 //1+0*10=1 //1+1*100=101 //101+1*1000=1101
i=i*10;//1*10=10//10*10=100 //100*10=1000 //10000
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"Decimal number "<<num<<" in binary is: "<<s<<endl;//1101

return 0;
}
/*
Enter a decimal number:13
r=1 n=6 s=1 i=10
r=0 n=3 s=1 i=100
r=1 n=1 s=101 i=1000
r=1 n=0 s=1101 i=10000
Decimal number 13in binary is: 1101
*/
//Binary to Decimal
#include<iostream>
using namespace std;
#include<math.h>

int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a binary number:";//1101=13
cin>>num;
int n,r,i=0;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%10;//
n=n/10;//
s=s+r*pow(2,i);//
++i;
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"binary number "<<num<<" in Decimal is: "<<s<<endl;//1101

return 0;
}
/*
manin()
Enter a binary number:1101
r=1 n=110 s=1 i=1
r=0 n=11 s=1 i=2
r=1 n=1 s=5 i=3
r=1 n=0 s=13 i=4
binary number 1101 in Decimal is: 13
*/
//Sum of digits of a numbers
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1//1/10=0
sum=sum+r;//4//4+3//4+3+2//4+3+2+1=10
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//10
return 0;
}
//Reverse Number
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//4321
return 0;
}
//Pallindrom number
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
if(num==sum)
{
cout<<"Its a pallindrom "<<num<<" is equal to "<<sum<<endl;//4321
}
else
{
cout<<"Not a pallindrom.\n";
}
return 0;
}
//Reversing String
#include<iostream>
using namespace std;
#include<string.h>
void strRev(char *arr);

int main()
{
cout<<"manin()\n";
char arr[]="Hello";
///*
int result;
char *end;
char *start;
end=arr;
start=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<=l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
//*/
cout<<"reversed string is:"<<arr<<endl;
cout<<"\nAgain reversing using function:\n";
strRev(arr);
cout<<"arr is now again: "<<arr<<endl;
//cout<<"Reverse string is: "<<strRev(arr)<<endl;
return 0;
}
void strRev(char *arr)
{
char *start=arr;
char *end=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
}
/*
manin()
reversed string is:olleH
Again reversing using function:
arr is now again: Hello
*/

C program to merge two sorted arrays. Array Union

//C/C++/C Plus Plus program to merge two sorted arrays
//C/C++/C Plus Plus program to find union of two sorted arrays
#include<iostream>
using namespace std;
#include<stdio.h>

int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5,7,8,9};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
{
printf("%d",arr1[i]);
i++;
}
else if(arr2[j]<arr1[i])
{
printf("%d",arr2[j]);
j++;
}
else //arr[i]==arr[j]
{
printf("%d",arr2[j]);
i++;
j++;
}
}
while(i<n1)
printf("%d",arr1[i++]);
while(j<n2)
printf("%d",arr2[j++]);

cout<<endl;
}
//output
//12345789

C program to find common numbers in two sorted arrays. Array intersection

//C/C++/C Plus Plus program to find common numbers in two sorted arrays
//C/C++/C Plus Plus program to find intersection of two sorted arrays
//C/C++/C Plus Plus program to find common elements of two sorted arrays
#include<iostream>
using namespace std;

int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
i++;
else if(arr2[j]<arr1[i])
j++;
else //arr[i]==arr[j]
{
cout<<"common elements are:"<<arr2[j]<<endl;
i++;
j++;
}

}
}

C Program for sorting an array using Bubble Sort and Insertion Sort

#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int arr[20],n,i,j,t;
cout<<"Enter the number of elements in array:"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0;i<n;i++)
cin>>arr[i];

cout<<"Entered the elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";

/*
cout<<"Bubble sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
cout<<n-i-1<<" "<<j<<" "<<j+1<<" "<<endl;
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
*/
//OR
/*
Selection sort: By first scanning the entire list before locating the exact pair of numbers to swap, only two writes to memory are performed by Selection Sort for each O(n) scan,whereas
Bubble Sort does writes on each and every comparison. So, Bubble Sort does O(n^2) writes. while selection sort does O(n) writes to mwmory.
*/
cout<<"\nSelection sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)//mind n-1
{
for(j=i+1;j<n;j++) //mind n
{
if(arr[i]>arr[j])
{
cout<<n<<" "<<i<<" "<<j<<" "<<endl;
t=arr[j];
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}


cout<<"Sorted array elements are:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";

cout<<endl;
return 0;
}
/*
//Selection Sort:
manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
4 1 2
4 2 3
4 3 4
4 4 5
3 2 3
3 3 4
3 4 5
2 3 4
2 4 5
1 4 5
Sorted array elements are:
1 2 3 4 5

//Bubble sort

manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
5 0 1
5 0 2
5 0 3
5 0 4
5 1 2
5 1 3
5 1 4
5 2 3
5 2 4
5 3 4
Sorted array elements are:
1 2 3 4 5
*/
/*
In Bubble sort , at every iteration you find a largest number and push it to bottom (Bubble out larger number)
In Insertion sort you have two regions one sorted and another unsorted.
At Every Iteration you pick up an element from unsorted region and insert at proper location in Sorted region.

Insertion Sort and Bubble sort both have Worst Case O(N^2).
But if the array is mostly sorted Insertion Sort will perform better
For both insertion and bubble sort worst case is O(n^2)
*/

C++ STL interview questions

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?(except when erased member is first or last member of container)
Q) What is the difference between capacity and size in vector container in STL?
Q) If initially size allocated to vector is 10. What would be the capacity of the vector? Will it be doubled?
Q) Write a program to demonstrate vector's algorithms ?
Q) Write a program to demonstrate map and multi map's algorithms?
Q) Write a program to demonstrate set and multi set's operations ?
Q) What is the return type of find algorithm in STL container?
Q) Write a program to find the  first match of pattern in given strings and its position? Use vector of strings?
Q) Write a program to find all matches of pattern in given strings and its position? Use vector of strings?
Q) What is the difference between array an vector?
Q) What is the difference between vector, list, set and map?
Q) Why vectors are thread safe?

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?
Invalidation  in vector means pointing out side of range of vector or pointing to altogether different value.
Insertion consequence in a vector:
i)All iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated.
ii)Erase consequences in vector: 
Every iterator and reference after the point of erase is invalidated.
iii)Resize effect in vector:
As per insertion and erase.
 example code of vector invalidation in c++ STL vector:
#include<iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
    int arr[] = { 10, 20, 30 };

    std::vector<int> vec(arr, arr + 3);
    // vector contains 1, 2, 3
        //size 3 and capasity 4

    std::vector<int>::iterator i = vec.begin();
    cout <<"*i="<< *i << endl; // prints 10
    int &ref = *i;
    cout <<"ref="<<ref << endl; // prints 10

    vec.resize(5, 100);
//vector now contains 1, 2, 3, 100, 100
//now capasity is 8 > size 5

    // WRONG! might work, crash or invalid result
    cout <<"*i=="<< *i << endl; // prints 0

    // WRONG! invalid reference
    cout <<"ref=="<<ref << endl; // prints 0

   return 0;
}

STL Map all operations example - map all algorithms

What is a map?
A map is an associative container which stores elements in key-value pair.
By default elements are stored in sorted fashion in ascending order of key. Binary search tree is internal data structure to implement maps.
How to insert in a map?
i) using 'insert" algorithm or
ii)using [key]=value style.
What is the difference between above two ways of insertion in maps?
What happens when a value is inserted in a map    ?
It depends on what algorithm has been used to insert.
i)If "insert.(pair<keyType,valuType>(key,value))" is used then value is simply gets ignored if that key already exists.
ii)If [key]=value is used then new value gets replaced if that key already exists.
iii)If at(key)=value is used then also new value is update to key.
How to delete using key?
By "find" and "erase" algorithm.
C++ MAP STL example code:
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
map<int,string> m;//actually <string, int> example is more used
m.insert(pair<int,string>(1,"Ram"));
m.insert(pair<int,string>(4,"Ram"));
m.insert(pair<int,string>(8,"Ram"));
m.insert(pair<int,string>(3,"Ram"));
m.insert(pair<int,string>(5,"Ram"));
m.insert(pair<int,string>(500,"Ram"));
m.insert(pair<int,string>(50,"Ram"));
m.insert(pair<int,string>(100,"Ram"));
m[1000]="Supreme";


cout<<"map is:"<<endl;
map<int,string>::iterator itr;
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;//sorted keys

cout<<"Erase all with key 4"<<endl;
int del=m.erase(4);
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"erase all less than key 8"<<endl;
m.erase(m.begin(),m.find(8));
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

//find(const g) – Returns an iterator to the element with key value ‘g’ in the map if found, else returns the iterator to end
cout<<"Finding key 100 and deleting it."<<endl;
map<int,string>::iterator itr2=m.begin();
itr2=m.find(100);
if(itr2!=m.end())
{
cout<<"100 found"<<endl;
m.erase(itr2);
//m.at(100) = "NewValue";
}
else
{
cout<<"100 not found"<<endl;
}
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Deleting key 50"<<endl;
m.erase(50);
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Inserting using at(key)"<<endl;
m.at(8) = "Raheem";
m.at(500) = "Jesus";
//m.at(100) = "God";//out of range when tries to insert at a key which does not exists
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Find(key)->second display."<<endl;
cout << "8 => " << m.find(8)->second<<endl;
cout << "500 => " << m.find(500)->second<<endl;
//cout << "500 => " << m.find(100)->second<<endl;//empty

cout<<endl;
return 0;
}
Example 2:
What is the difference between two different ways of inserting into a map?
What will happen if duplicate values are inserted in a map?
i) inserting using algorthm"insert" : Does nothing. Key holds the old value.
ii) inserting using [] : update the key with new value.
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
cout<<""<<endl;
map<string,int> m;
//In map values are inserted in asending order of keys.
m.insert(pair<string,int> ("Manoj",5));
m.insert(make_pair("Sony",2));
m.insert(make_pair("Aditi",3));
//insert resturns false if same key is inserted again.
//Nothing happens if we insert duplicatge key.
m.insert(make_pair("Aditi",4));//Not inserted as key Aditi already exists.
m.insert(make_pair("Aditi",5));//Not inserted as key Aditi already exists.
//Different keys can have the same value as another key's value.
m.insert(make_pair("Biswa",3));//Biswa inserted after Aditi.

map<string,int>::iterator itr=m.begin();
while(itr!=m.end())
{
cout<<itr->first<<" "<<itr->second<<endl;
itr++;
}
/*
Aditi 3
Biswa 3
Manoj 1
Sony 2
*/
cout<<"Another map to show second way of inserting elements:\n";
map<string,int> m2;
m2.insert(make_pair("AAA",1));
m2.at("AAA")=300;//now value of key AAA is also gets updated
m2["BBB"]=2;//now value of key BBB is 2
m2["BBB"]=3;//now value of key BBB is 3
m2["BBB"]=4000;//now value of key BBB is 4000
map<string,int>::iterator itr2=m2.begin();
while(itr2!=m2.end())
{
cout<<itr2->first<<" "<<itr2->second<<endl;
itr2++;
}
/*
AAA300
BBB 4000
*/
return 0
 }
Multi Map example to hold duplicate keys:
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
cout<<""<<endl;
multimap<string,int> m;
//In map values are inserted in asending order of keys.
m.insert(pair<string,int> ("Manoj",5));
m.insert(make_pair("Sony",2));
m.insert(make_pair("Aditi",3));
m.insert(make_pair("Aditi",4));//Another Aditi with new value 4
m.insert(make_pair("Aditi",5));//Another Aditi with new value 5
m.insert(make_pair("Biswa",3));//Biswa inserted after Aditi.

multimap<string,int>::iterator itr=m.begin();
while(itr!=m.end())
{
cout<<itr->first<<" "<<itr->second<<endl;
itr++;
}
/*
Aditi 3
Aditi 4
Aditi 5
Biswa 3
Manoj 5
Sony 2
*/
cout<<"---map example to find a key"<<endl;
cout<<"---find returns iterator to the found keys"<<endl;
cout<<"---find returns false so garbage value"<<endl;
itr=m.begin();
cout<<"m.find(Aditi)="<<m.find("Aditi")->second<<endl;//3//first match only.
cout<<"m.find(Manoj)="<<m.find("Manoj")->second<<endl;//5
cout<<"m.find(Sahu)="<<m.find("Sahu")->second<<endl;//garbage

itr=m.begin();
if(m.find("Aditiii")!=m.end())
cout<<itr->first<<" found and value is "<<itr->second<<endl;
else
cout<<"Not found"<<endl;

return 0;
}
/*
Aditi 3
Aditi 4
Aditi 5
Biswa 3
Manoj 5
Sony 2
---map example to find a key
---find returns iterator to the found keys
---find returns false so garbage value
m.find(Aditi)=3
m.find(Manoj)=5
m.find(Sahu)=223444160
Not found
*/ 
In multi map "find" return the value of first key only.
How to find all the values associated with duplicate key?
Using the algorithm equal_range("key").
Count can be taken by algorithm "distance" 

What are QML FAQ in interviews?

Q) What is Qml ?
QML is the name of the language (just like C++, which is another language...)
QML stands for Qt Meta Language or Qt Modelling Language is a user interface markup language.
Q) How to call c++ call from QML?
QML call C + + methods with the Qt meta-object system. Like below:
onClicked: parent.color = parent.randomColor ()

Q) What are Four ways of integreting C++ with Qml?
Subclassing QQuickItem: QQuickItem allows you to write your own visual and non-visual QML items using C++.
Registering C++ types with QML: C++ classes can be registered with the QML type system, allowing them to be instantiated as QML types.
Registering Context Properties: QObjects can be registered with the QML context, allowing their properties to be directly accessed.
Accessing QML objects through the QML object tree: All QML objects reside in a tree hierarchy and can be accessed via the root of the tree.
http://www.ics.com/blog/multilayered-architecture-qt-quick

Q) How to call a C++ function from a qml?
Through setcontext property.
Note
Loading a main.qml with a simple Item as the root type through the QmlApplicationEngine will not show anything on your display, as it requires a window to manage a surface for rendering. The engine is capable of loading qml code which does not contain any user interface (e.g plain objects). Because of this it does not create a window for you by default.
The qmlscene or the new qml runtime will internally first check if the main qml file contains a window as a root item and if not create one for you and set the root item as a child to the newly created window.

Q)What is Q_INVOKABLE?
Add callable methods using Q_INVOKABLE or Qt slots, and connect to Qt signals with an onSignal syntax

Q)How to call a QML function from c++?
QML functions can be called from C++ and vice-versa.
All QML functions are exposed to the meta-object system and can be called usingQMetaObject::invokeMethod(). Here is a C++ application that uses this to call a QML function:
// MyItem.qml
import QtQuick 1.0
Item {
    function myQmlFunction(msg) {
        console.log("Got message:", msg)
        return "some return value"
    }
}
// main.cpp
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();
QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
        Q_RETURN_ARG(QVariant, returnedValue),
        Q_ARG(QVariant, msg));
qDebug() << "QML function returned:" << returnedValue.toString();
delete object;

Q)How to call a C++ function from QML ?
A C++ function can be called from a qml using set contextpropery in c++.
http://doc.qt.io/qt-4.8/qtbinding.html
All QML signals are automatically available to C++, and can be connected to using QObject::connect() like any ordinary Qt C++ signal.
The signal is sent to QML, and the slot is invoked from QML.
There are different ways to send signals from C++ to QML and back. In this article, we show how to do this by embedding a C++ class directly into QML. This has the advantage that no Qt::connect connections need to be set-up manually.
In our example, we have a Receiver class that is implemented in C++.
This class defines a signal sendToQml and a slot receiveFromQml.
 Both have an integer parameter.
The signal is sent to QML, and the slot is invoked from QML.
Example:
//signal_slot.pro
TEMPLATE = app
QT += qml quick
#export QT_SELECT=5
SOURCES += main.cpp \
    receiver.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Default rules for deployment.
include(deployment.pri)
HEADERS += \
    receiver.h
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "receiver.h"
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    Receiver receiver;
    QQmlContext* ctx = engine.rootContext();
    ctx->setContextProperty("receiver", &receiver);
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    receiver.sendToQml(43);
    //QDeclarativeView view;
    //view.rootContext()->setContextProperty("_EBSCModel",m_EBSCDtcDataModel);
    //sourcePath = "qrc:///DTC/qml/ITSDTC.qml";
    //view.setSource(QUrl(sourcePath));
    return app.exec();
}
//receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include <QObject>
class Receiver : public QObject
{
    Q_OBJECT
public:
    explicit Receiver(QObject *parent = 0);
signals:
    void sendToQml(int count);
public slots:
    void receiveFromQml(int count);
};
#endif // RECEIVER_H
//receiver.cpp
#include "receiver.h"
#include <QDebug>
Receiver::Receiver(QObject *parent) :
   QObject(parent)
{
}

void Receiver::receiveFromQml(int count) {
    qDebug() << "Received in C++ from QML:" << count;
}
//main.qml
import QtQuick 2.2
import QtQuick.Window 2.1
Window {
    id: test
    visible: true
    width: 200
    height: 50
    Connections {
        target: receiver
        onSendToQml: {
            console.log("Received in QML from C++: " + count)
        }
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            receiver.receiveFromQml(42);
        }
    }

    Text {
        text: qsTr("Press me to send a signal to C++")
        anchors.centerIn: parent
    }
}