Search This Blog

Saturday, October 31, 2015

Debugging with GDB

GDB is open source GNU debugger which is used to debug and examine faulty codes. GDB has broader application. I will try to pull most of it from beginner to some extent of advance level.

GDB has bunch of commands and their arguments. Lets starts with some useful commands

sample.c

 1 #include <stdio.h>
  2 int main(int argc, char *argv[])
  3 {
  4         int i = 0;
  5         for( i = 0;i< 2;i++)
  6         {
  7                 printf("Hello World\n");
  8         }
  9 }
 10
This is sample code taken for reference.
compilation of code
$gcc -g -o run sample.c


option -g is used to add all symbols.
Running Code in GDB

$gdb <.exe>

This command is used to start an executable file
madcoder@linux:~/Desktop/Laboratory/gdb$ gdb run
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from run...done.
(gdb) <this is the area where most of the gdb commands get executed>

Once this appears then its time to execute gdb commands.
1. run command
(gdb) run or r

This command is used to run code or program. Once this command is invoked code will run till output unless any checkpoints inserted in between.  
 ex:
(gdb) r
Starting program: /home/madcoder/Desktop/Laboratory/gdb/run
Hello World
Hello World
[Inferior 1 (process 3750) exited with code 014]
(gdb)
This is the expected output of above program.

2. Start command
(gdb) start 

This command starts executing the code and pauses at beginning of main() function. Start command creates a temporally  break point at the starting of the main function.

ex:
(gdb) start
Temporary breakpoint 1 at 0x40053c: file sample.c, line 4.
Starting program: /home/madcoder/Desktop/Laboratory/gdb/run

Temporary breakpoint 1, main (argc=1, argv=0x7fffffffe008) at sample.c:4
4        int i = 0;
(gdb)

pause at line number 4. starting of program, hereafter other gdb commands can be used to get into code for debugging prospective.

3. List command
This command 
(gdb) list


ex:
(gdb) list
1    #include <stdio.h>
2    int main(int argc, char *argv[])
3    {
4        int i = 0;
5        for( i = 0;i<2;i++)
6        {
7            printf("Hello World\n");
8        }
9    }  
10  
(gdb)

# Printing values in GDB
(gdb) print or p

Using this command one can print value of a variable or value of an address at any break point or watch point or aborted point.

(gdb) n
20            var1 = my_fun(i, var1);
(gdb)
18        for(i = 0; i <10; i++)
(gdb)
20            var1 = my_fun(i, var1);
(gdb)
18        for(i = 0; i <10; i++)
(gdb)
20            var1 = my_fun(i, var1);
(gdb)
18        for(i = 0; i <10; i++)
(gdb)
20            var1 = my_fun(i, var1);
(gdb) print i
$2 = 5



After stepping into 5 time into loop the incremented value of variable i can be obtained. Stepping into code using GDB, will see in later command practice.

Printing values using print command is very useful when it comes to print a linked list of a structure. More practice with print command will help more in debugging specially in case of logical errors.




#Setting Break point and Watch point
(gdb) break or b <line number or filename.c:line number>

Breakpoint setting will give more exposer to bug fixing. here the point where all interviewers grill the candidates. But here i will discuss few points where programmers should not use breakpoints. Breakpoint is not applicable for library functions(Static and Dynamic). If some code is running on device or real time hardware and the there is no possibility of altering the sequence of running, there using breaking points may lead to major harm. In such cases programmer can create another instance of the terminal and there they can attach that process using GDB. Ex.

Terminal -1 Code is running unstoppable, open a new terminal and run gdb alon and try to attach current running process with PID.

(gdb) attach <pid>
and here you can check for the parameter  and examine the behaviour of code.


# Passing command line arguments in GDB
M-1
$gdb --args arg1 arg2 ... ./a.out
M-2
$gdb ./a.out
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
.........
.........
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
(gdb) run arg1 arg2 arg3


















Write a C program to calculate your age.

1:  #include <stdio.h>  
2:  #include <stdlib.h>  
3:  #include <time.h>  
4:  #define YEAR_FACTOR 1900  
5:  #define MONTH_FACTOR 1  
6:  int main(int argc, char *argv[])  
7:  {  
8:      struct tm *tm;  
9:      time_t ltime, cts;  
10:      int year = 0, month = 0, date = 0;  
11:      int age_year = 0, age_month = 0, age_day = 0, age_hrs = 0, age_minut = 0,   
12:  age_second = 0;  
13:      printf("Enter your DOB\n");  
14:      printf("Data(The day you born):");  
15:      scanf("%d",&date);  
16:      printf("Month:");  
17:      scanf("%d",&month);  
18:      printf("Year:");  
19:      scanf("%d",&year);  
20:      //Get current time stamp  
21:      cts = time(NULL);  
22:      tm = localtime(&cts);  
23:      age_year = (tm->tm_year+YEAR_FACTOR) - year;  
24:      age_month = (tm->tm_mon+MONTH_FACTOR) - month;  
25:      age_day = tm->tm_mday - date;  
26:      printf("Year : %d\tMonth : %d\tDay : %d\n",age_year,age_month,  
27:                                                      age_day);  
28:  }  

Friday, October 30, 2015

Find greates among three numbers using ternary operator in C

1:  #include <stdio.h>  
2:  main()  
3:  {  
4:    int a,b,c,k;  
5:    printf("Enter Three Numbers:");  
6:    scanf("%d",&a);  
7:    scanf("%d",&b);  
8:    scanf("%d",&c);  
9:    k = a>b?a>c?a:c>b?c:b:b>c?b:c;  
10:    printf("Largest Number is %d\n",k);  
11:  }   

Factorial of number in C.

1:  #include <stdio.h>  
2:  long factorial(int n)  
3:  {  
4:    if(n ==0)  
5:    {  
6:      return 1;  
7:    }  
8:    return (n * factorial(n-1));  
9:  }  
10:  main()  
11:  {  
12:    int n;  
13:    long fact = 0;  
14:    printf("Enter a Number : ");  
15:    scanf("%d",&n);  
16:    fact = factorial(n);  
17:    printf("Result = %ld\n",fact);  
18:  }   

string reverse in C

1:  M#1  
2:  void own_strrev(char *str)  
3:  {  
4:    char *start = str;  
5:    char *end = str + strlen(str) -1;  
6:    char ch;  
7:    printf("Start : %c\tend : %c\n", *start, *end);  
8:    while(end > start)  
9:    {  
10:      ch = *start;  
11:      *start = *end;  
12:      *end = ch;  
13:      start++;  
14:      end--;  
15:    }  
16:  }  
17:  M#2  
18:  char *own_strrev(const char *str)  
19:  {  
20:    int len = strlen(str),i=0;  
21:    char *ptr = malloc(len+1);  
22:    for(i=0,len -=1; len>=0;i++,len--)  
23:    {  
24:      ptr[i] = str[len];  
25:    }  
26:    ptr[i] = '\0';  
27:    return ptr;  
28:  }  

Wednesday, October 28, 2015

write your own strstr function.

1:  #include <stdio.h>  
2:  #include <string.h>  
3:  void *my_strstr(char *str1,char *str2)  
4:  {  
5:    int l1,l2;  
6:    l2 = strlen(str2);  
7:    if(!l2)  
8:      return (char *)str1;  
9:    l1 = strlen(str1);  
10:    while(l1>=l2)  
11:    {  
12:      l1--;  
13:      if ( !memcmp(str1,str2,l2))  
14:      {  
15:        return (char *)str1;  
16:      }  
17:      str1++;  
18:    }  
19:    return NULL;  
20:  }  
21:  main()  
22:  {  
23:    char str1[100] = "helloworld";  
24:    char str2[100] = "llo";  
25:    char *temp = my_strstr(str1,str2);  
26:    printf("%s\n",temp);  
27:    temp = strstr(str1,str2);  
28:    printf("%s\n",temp);  
29:  }  

write string reverse program in c

1:  #include <stdio.h>  
2:  #include <string.h>  
3:  void my_strrev(char *str)  
4:  {  
5:    char temp;  
6:    char *start = str;  
7:    char *end = str+strlen(str)-1;  
8:    while(end>start)  
9:    {  
10:      temp = *start;  
11:      *start = *end;  
12:      *end = temp;  
13:      start++;  
14:      end--;  
15:    }  
16:    printf("str = %s\n",str);  
17:  }  
18:  main()  
19:  {  
20:    char str[100] = "hello World";  
21:    my_strrev(str);  
22:    printf("%s\n",str);  
23:  }  

sort all given strings

1:  #include <stdio.h>  
2:  #include <string.h>  
3:  int my_strcmp(char *str1,char *str2)  
4:  {  
5:    while(1)  
6:    {  
7:      if ( *str1 != *str2 )  
8:        return (*str1 > *str2 ? 1:-1);  
9:      if (str2)  
10:        break;  
11:      str1++;  
12:      str2++;  
13:    }  
14:  }  
15:  void string_sorting(char str[][20],int cnt)  
16:  {  
17:    char temp[100];  
18:    int i = 0,j=0,k=0;  
19:    while(i<cnt)  
20:    {  
21:      for(j=0;j < cnt-1;j++)  
22:      {  
23:        if ( 0 < strcmp(str[j],str[j+1]))  
24:        {  
25:          strcpy(temp,str[j]);  
26:          strcpy(str[j],str[j+1]);  
27:          strcpy(str[j+1],temp);  
28:        }  
29:      }  
30:      i++;  
31:    }  
32:  }  
33:  main()  
34:  {  
35:    int i=0;  
36:    char str[8][20] =  
37:  {"orange","apple","mango","kiwi","pear","cherry","plum"};  
38:    for(i=0;i<7;i++)  
39:    {  
40:      printf("%s\n",str[i]);  
41:    }  
42:    string_sorting(str,7);  
43:    printf("\n==========================\n");  
44:    for(i=0;i<7;i++)  
45:    {  
46:      printf("%s\n",str[i]);  
47:    }  
48:  }  

Sort all characters in a given string

1:  #include <stdio.h>  
2:  #include <string.h>  
3:  void char_sorting_ptr(char *str,int sz)  
4:  {  
5:    char temp,*p = str,*c = str;  
6:    int i = 0,j=0;  
7:    while( i < sz)  
8:    {  
9:      for(j=0,p=str;j < sz-1;j++)  
10:      {  
11:        if ( *p > *(p+1))  
12:        {  
13:          temp = *(p+1);  
14:          *(p+1) = *p;  
15:          *p = temp;  
16:        }  
17:        p++;  
18:      }  
19:      i++;  
20:    }  
21:  }  
22:  void char_sorting(char *str,int sz)  
23:  {  
24:    char temp;  
25:    int i = 0,j=0;  
26:    while( i<sz)  
27:    {  
28:      for(j=0;j<sz-1;j++)  
29:      {  
30:        if ( str[j] > str[j+1])  
31:        {  
32:          temp = str[j];  
33:          str[j] = str[j+1];  
34:          str[j+1] = temp;  
35:        }  
36:      }  
37:      i++;  
38:    }  
39:  }  
40:  main()  
41:  {  
42:    char str[100] = "mynameisjohn";  
43:    char_sorting_ptr(str,strlen(str));  
44:    printf("Sorted String : %s\n",str);  
45:  }  

write a program to remove particular character from a given string

1:  #include <stdio.h>  
2:  #include <string.h>  
3:  void char_remove(char *str,char c)  
4:  {  
5:    char *temp = str;  
6:    char *cur = str;  
7:    int count = 0;  
8:    while(*temp)  
9:    {  
10:      if ( *temp == c)  
11:      {  
12:        temp++;  
13:        count++;  
14:      } else {  
15:        *cur++ = *temp++;  
16:      }  
17:    }  
18:    if ( count == 0)  
19:      printf("Char %c is not fount in the string\n",c);  
20:  }  
21:  main()  
22:  {  
23:    char str[100] = "aaaabbbbcccccdddddbbbbbeeeebbbbfffff";  
24:    char ch;  
25:    printf("Enter char to be string:");  
26:    scanf("%c",&ch);  
27:    char_remove(str,ch);  
28:    printf("Str : %s\n",str);  
29:  }   

Reverse all words in a given string.

1:  #include <stdio.h>  
2:  #include <stdlib.h>  
3:  #include <string.h>  
4:  void reverse(char *start,char *end)  
5:  {  
6:    char temp;  
7:    while(1)  
8:    {  
9:      if ( end > start)  
10:      {  
11:        temp = *start;  
12:        *start = *end;  
13:        *end = temp;  
14:      } else {  
15:        break;  
16:      }  
17:      start++;  
18:      end--;  
19:    }  
20:  }  
21:  void word_reverse(char *str)  
22:  {  
23:    int xlen= strlen(str);  
24:    char *start,*end,temp,*rev = str;  
25:    start = str;  
26:    end = str+xlen-1;  
27:    reverse(start,end);  
28:    start = str;  
29:    while(1)  
30:    {  
31:      if(*rev != ' ' && *rev != '\0' )  
32:      {  
33:        rev++;  
34:      } else {  
35:        reverse(start,rev-1);  
36:        start = rev+1;  
37:        rev++;  
38:      }  
39:      if(rev)  
40:        break;  
41:    }  
42:  }  
43:  main()  
44:  {  
45:    char str[100] = "my name is john";  
46:    word_reverse(str);  
47:    printf("Revrse : %s\n",str);  
48:  }  

write your own memmove program without overlapping constrain.

1:  #include <stdio.h>  
2:  #include <string.h>  
3:  void * my_memmove(char *dest,char *src,int count)  
4:  {  
5:    char *temp;  
6:    char *s;  
7:    if ( dest <= src) {  
8:      temp = dest;  
9:      s = src;  
10:      while(count--)  
11:        *temp++ = *s++;  
12:    } else {  
13:      temp = dest;  
14:      temp += count;  
15:      s = src;  
16:      s += count;  
17:      while(count--)  
18:        *--temp = *--s;  
19:    }  
20:    return dest;  
21:  }  
22:  main()  
23:  {  
24:    char str[100] = "abcdefghijklmnopqrstuvwxyz";  
25:    my_memmove(str+5,str,4);  
26:    printf("my_memmove = %s\n",str);  
27:    strcpy(str,"abcdefghijklmnopqrstuvwxyz");  
28:    memmove(str+5,str,4);  
29:    printf("sys_memmove = %s\n",str); // compare with original memmove  
30:    strcpy(str,"abcdefghijklmnopqrstuvwxyz");  
31:    memcpy(str+5,str,4);  
32:    printf("sys_memcpy = %s\n",str); // and memcpy to check overlap  
33:  }   

count all repeated character in a given string.

1:  #include <stdio.h>  
2:  main()  
3:  {  
4:    char str[100] = "akjdl**&%$*(*(^%kdfja";  
5:    int arr[255] = {0}; // 255 for max ascii value  
6:    int i = 0;  
7:    for(i=0;str[i] != '\0';i++)  
8:      arr[str[i]]++;  
9:    for(i=0;i<255;i++)  
10:    {  
11:      if ( arr[i] >= 1)  
12:        printf("%c is repeated %d times\n",i,arr[i]);  
13:    }  
14:  }  

Write a program which count all consecutive characters in a given string and write display string as in given example. e.g str = "aaabbbcc"; O/P string is "3a3b2c"

1:  #include <stdio.h>  
2:  #include <string.h>  
3:  main()  
4:  {  
5:    char *str = "aabbcc***^^^^&&&&ffff";  
6:    char opstr[100] = {0};  
7:    char c,tb[5];  
8:    int count = 1;  
9:    while(*str)  
10:    {  
11:      if ( *str == *(str +1) )  
12:      {  
13:        c = *str;  
14:        str++;  
15:        count++;  
16:      } else {  
17:        sprintf(tb,"%d",count);  
18:        strcat(opstr,tb);  
19:        sprintf(tb,"%c",c);  
20:        strcat(opstr,tb);  
21:        str++;  
22:        count=1;  
23:      }  
24:    }  
25:    printf("%s\n",opstr);  
26:  }