Skip to main content

Interview Debugging Techniques in C


                                                                   DATA TYPE


Length of the Variable name not beyond 32 characters


endian : process of bytee ordering

In litte endian , ABCD is stored as DCBA
In big endian ,  ABCD is stored as ABCD


Enum is “ Sequence set of interger constants “


Cycle
           Integer, Char  -> yes
           Others            -> no
           Enum             -> no

Range

       
        Escape sequenceOctal Char Constant

         Octal Char Constant   ->  '\000' to  '\377'
        Escape sequence          ->  '\a'     to   '\r'

           For Float or Double
                                             max range : INF
                                             min range : -INF


Signed or Unsigned

                    
                            Integer, Char  -> yes
                            Others            -> no

NULL Char Constant


                            Size            : 1 Byte
                            ASCII no   :  0


Define in all following Header Files :

                                     STDIO.H, STDLIB.H, MATH.H, STRING.H,

                                    TIME.H, WCHAR.H, STDDEF.H, LOCAL.H

EOF Char Constant

                          Size            : 1 Byte
                          ASCII no :  -1 ( mostly )  ( is -1 for gcc and g++ compiler )
                                               i.e depent upon compiler.


In C, data type of character constants is int, but in C++, data type of same is char


                   printf("%d", sizeof('a'));    In C :: 4 bytes  Whereas In Cpp :: 1 byte



 
FLOAT data is always stored in “ mantissa and exponent format ”

int8_t
int16_t
int32_t
uint8_t
uint16_t
uint32_t
 
             These are an optional item in the standard, but it must be a hidden feature, because people are constantly redefining them. One code base I've worked on (and still do, for now) has multiple redefinitions, all with different identifiers.

 Most of the time it's with preprocessor macros:
 
#define INT16 short
#define INT32  long

And so on. It makes me want to pull my hair out. Just use the freaking standard integer typedefs!
 

Typedef does not creates the new data types.




Implement Your Own sizeof


Here is an implementation.

                                                       #define my_sizeof(type) (char *)(&type+1)-(char*)(&type)



printf() returns the number of characters successfully written on the output

scanf() returns number of items successfully read.

return type of getchar(), fgetc() and getc() is int (not char)



                                                               OPERATORS


  • Associativity of a COMMA ( , ) Operator  =>    Left to Right

  • No Power Operator in C Language

  • # is a string forming operator that converts a non-string to string in perprocess directives

  • In  Relative operators or Logical operator  => Returns only    “  1 or 0 “

  • Bitwise Operator
                                                   Interger --- yes
                                                  Foat ---- no

                         +i  =>Dummy Statment.

                     ~ 0==(unsigned int) -1 ==65535

 

Adding two numbers (a and b) without using any operators:

printf("%d", printf("%*s%*s",a,"\r",b,"\r") );

it prints a+b.

                                                                 Control Structures

IF Statments

  • Hanging if is NOT allow in c
  • else statment is optional


Switch Case

  • Without Case  --- > No error and No Output
  • Case must be in Interger Constant or Char Constant or Expression Constant
  • Last Case can NOT be empty
  • Duplicate Case is NOT allowed
  • Nested Switch is possible
  • Dont use continue”  within Switch Case


GOTO Statments

  • GOTO is functional scoping , so they should be in same function.
  • Break is simiarly to the Goto Statement.



                                                                             LOOP


Loop is Alternate of function recursion

Types

  1. For---finite loop
  2. While---Unknown loop
  3. Do While--- At Least One Time

Loop Counter

  • Not initalized   --- Odd loop
  • It can be Interger, Character, Float
  • It has own Block Scoping

when control reached coutinue statement , control is passes to condition statement of loop   


The comma operator isn't widely used. It can certainly be abused, but it can also be very useful. This use is the most common one:
 
for (int i=0; i<10; i++, doSomethingElse())
{
  /* whatever */
}

But you can use this operator anywhere. Observe:
 
int j = (printf("Assigning variable j\n"), getValueFromSomewhere());

Each statement is evaluated, but the value of the expression will be that of the last statement evaluated.

 

                                                                          POINTER

Generic Pointer

  • NO dereference
  • NO Arithmetic operator are allowed
  • Return type of malloc or calloc function

Null Pointer
  • NO dereference
  • (void *) 0->Represent NULL pointer

Far Pointer

  • Arithmetic operator are done at offset address
  • Beyond 64 KB process menory


Huge Pointer ( Normalized Pointer )

  • Arithmetic operator are done at absolute address

Tricks

                                 int *ptr = &a[0];
                                printf(“%d”,(ptr+2)-ptr);


                                o/p : 2


C allows a void* pointer to be assigned to any pointer type without a cast, whereas C++ does not;

How to read the Pointer ?


Hint : Reads right to left <----  without braces
High prioabities to braces

Example:

  • int *p ->pointer to interger
  • int *p[ ]-> array of pointer to the interger
  • int (*p)[ ]->pointer to array of interger
  • int *p( )->p is function which returns pointer to interger
  • int (*p)( )-> pointer to the function which returns interger 



Pointer vs Array in C


Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being:
1)  sizeof operator

  •  sizeof(array) returns the amount of memory used by all elements in array
  •  sizeof(pointer) only returns the amount of memory used by the pointer variable itself
2)  & operator

  •  &array is an alias for &array[0] and returns the address of the first element in array
  •  &pointer returns the address of pointer
3) a String Literal initialization of a character array

  • char array[] = “abc” sets the first four elements in array to ‘a’, ‘b’, ‘c’, and ‘\0′
  • char *pointer = “abc” sets pointer to the address of the “abc” string (which may be stored in read-only memory and thus unchangeable)
4) Pointer variable can be assigned a value whereas array variable cannot be.
                      int a[10];
                 int *p;
                 p = a; /*legal*/
                 a = p; /*illegal*/
5) Arithmetic on pointer variable is allowed.
  • p++; /*Legal*/
  • a++; /*illegal*/




                                                                       STRING

 
When using sscanf you can use %n to find out where you should continue to read:
 
sscanf ( string, "%d%n", &number, &length );
string += length;
 
 

Apparently, you can't add another answer, so I'll include a second one here, you can use "&&" and "||" as conditionals:

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

int main()
{
   1 || puts("Hello\n");
   0 || puts("Hi\n");
   1 && puts("ROFL\n");
   0 && puts("LOL\n");

   exit( 0 );
}
 
This code will output:
 
Hi
ROFL

gets( ) 
  • doesn’t do any array bound testing.
  •  keeps on reading until it sees a newline character.

To avoid Buffer Overflow,

  •  fgets() should be used instead of gets() as fgets() 
  • makes sure that not more than MAX_LIMIT characters are read.

#define MAX_LIMIT 20
void read()
{
   char str[MAX_LIMIT];
   fgets(str, MAX_LIMIT, stdin);
   printf("%s", str);

   getchar();
   return;
}


if str[] is an auto variable then string is stored in stack segment, eg :str[]={'h', 'e', l', 'l', 'o', \0'};


Writable Stack Segment

char *getString( ){
char str[] = “hello”;
return str;
}             

// Returns Garbage Value because its get store in stack segement after function gets over ...value gets free or deleted  


if it’s a global or static variable then stored in data segmenteg:*str = ”hello”;


Read only string in a shared segment.

char *getString( ){
char *str = “hello”;
return str;
}             

// Returns String Value because its get store in data segement after function gets over ...value gets remained through out the program.   



my_strcat(dest, src) copies data of src to dest. 

To do so,
  • It first reaches end of the string dest using recursive calls my_strcat(++dest, src).
  • Once end of dest is reached, data is copied using

void my_strcat(char *dest, char *src){
  (*dest)? my_strcat(++dest, src): (*dest++ = *src++)? my_strcat(dest, src): 0 ;
}

(  OR  )

void my_strcat(char *dest, char *src){
   while(*dest)
             while( *dest++ = *src++ );
   return;
}


my_strcmp(a, b)

  • Returns 0 if strings a and b are same, otherwise 1. 
  • It recursively increases a and b pointers. At any point if *a is not equal to *b then 1 is returned.
  • If we reach end of both strings at the same time then 0 is returned.

int my_strcmp(char *a, char *b){
          return (*a == *b && *b == '\0')? 0 : (*a == *b)? my_strcmp(++a, ++b): 1;
}



 
For clearing the input buffer you can't use fflush(stdin).

The correct way is as follows: scanf("%*[^\n]%*c") This will discard everything from the input buffer.



Instead of
 
printf("counter=%d\n",counter);


Use
 
#define print_dec(var)  printf("%s=%d\n",#var,var);
print_dec(counter);
 
 
 

                                                                     FUNCTION

Fuction Return Type

  • Defalut Type -Interger
  • Stores -Stack
  • returns Only one at a time

Function Called

  • Function name followed by ()
  • Pointer to the Function
 
 
void myFunction(type* values) {
    while(*values) x=*values++;
}
 
myFunction((type[]){val1,val2,val3,val4,0});
 
 
it can even be used to instanciate linked lists...
 

 

 * character achieves this effect.

 
#include <stdio.h>
int main() {
    int a = 3;
    float b = 6.412355;
    printf("%.*f\n",a,b);
    return 0;
}
 
o/p : 6.412

In C, it might not be possible to have function names on left side of an expression, but it’s possible in C++.  

(  i.e ::  fun() = 10; )


Function pointers.
                    You can use a table of function pointers to implement, e.g., fast indirect-threaded code interpreters (FORTH) or byte-code dispatchers, or to simulate OO-like virtual methods.



Then there are hidden gems in the standard library, such as qsort(),bsearch(), strpbrk(), strcspn() [the latter two being useful for implementing a strtok() replacement].



A misfeature of C is that signed arithmetic overflow is undefined behavior (UB). So whenever you see an expression such as x+y, both being signed ints, it might potentially overflow and cause UB.



if(---------)  
printf("hello");  
else   
printf("hi");


Fill in the blanks so that neither hello nor hi would appear in output.

ans: fclose(stdout)


                                                                    STORAGE CLASS

C doesn’t allow multiple storage class specifiers for a variable.
  • Usage
  • Scope
  • Life Time
  • Storage
  • Default intial value

Types

  • extern
  • Static
  • Auto
  • Register
  • extern
  • Program Scoping  ( used in Library file )  Intial Value: 0



Static

  • File Scoping ( used in Library file )
  • Sharing the same menory location in different frames of funtion recurrsion
  • Over come the Dangling Pointer

Auto

  • Block Scoping
  • Default Storage Class  

Register

  • Created in CPU register if it is free
Local Variable
  1. auto
  2. static
  3. register


Function or Global variable

  1. static 
  2. extern

Function Parameter

  1. register


Printf and Scanf function is the ENEMY of the Register Storage Class


Static variable are load time entites while auto variable are run-time entity , Not intialized any loaad time variable by the run time variable.





                                                                    PREPROCESSOR

CPP is the name of the C Preprocessor

  1. “”         ----       Current Directory and included Directory
  2. <>        ----       Included Directory

Muti-White space characters embedded within the arguments passed to the macro are replaced by single white space



                                                                           STRUCTURE

Usage

  • Data Encapsulation
  • Memory Link
  • Bit-Fields (Offsetof – to measure byte offset)

Structure contain slack byte  ----      Imbalance Structure

Word Aligment is required    ----      Imbalance Structure to Balance Structure

“ struct ” keyword is needed in C Language, Not in Cpp by default it assing sturct during comiple time
 
 
 
 
 
 
initializing structure to zero
struct mystruct a = {0};
this will zero all stucture elements.
 

used bit fields but they sound cool for ultra-low-level stuff.

 
struct cat {
    unsigned int legs:3;  // 3 bits for legs (0-4 fit in 3 bits)
    unsigned int lives:4; // 4 bits for lives (0-9 fit in 4 bits)
    // ...
};

cat make_cat()
{
    cat kitty;
    kitty.legs = 4;
    kitty.lives = 9;
    return kitty;
}
 
This means that sizeof(cat) can be as small as sizeof(char).
 

 

 

C99 has some awesome any-order structure initialization.

struct foo{
  int x;
  int y;
  char* name;
};

void main(){
  struct foo f = { .y = 23, .name = "awesome", .x = -38 };
}
 
 

 

 

I discoverd recently 0 bitfields.

struct {
  int    a:3;
  int    b:2;
  int     :0;
  int    c:4;
  int    d:3;
};
 
which will give a layout of
 
000aaabb 0ccccddd
 
 
instead of without the :0;
 
0000aaab bccccddd
 
 
 
The 0 width field tells that the following bitfields should be set on the next atomic entity (char)
 
Nested Structure

  • Nested Inner Structure must be named before use the Outer Strutcure
  • Same Structure can NOT be nested within Same Structure ...
  • Where as we can go for POINTER is called Self-Referntial Structure
  • One Structure variable is asigned to another  Structure variable then Both are same Structure
Never Compare Two Structure Variables



                                                                           UNION

First member of Union 

  • Active Member
  • Initialized at time of Definition
  • NOT Reset

Used
  • Memory Optimization


FILE STRUCTURE

File
  • Media of storing data inside a Disk
  • Created in directory sector in Disk

Stream
  • Flow of Data from “ Buffer to Device or Device to Buffer ”
  • FIVE Predefined Stream
  1. stdin
  2. stdout
  3. stderr
  4. stdaux
  5. stdprn  (  when press CTRL +F9 )

Stream is NOT assoicated in memory its file descriptor value  = -1

*curp                  ---    Active File Pointer in Turbo C

getc()                  ---    Returns -1 When we press CTRL +Z
 
EOF macro         ---    1



                                                   COMMAND LINE ARUGUMENT

Main Function has Three Function Parameter

  • Arugument Counter --Interger
  • Arugument Vector--Array of String
  • Enviroment Vector--Array of String

All the Command line aruguments ---extern types


main ( )  --->   int main( extern int _argc, extern char **_argv)



                                                  DYNAMIC MEMORY ALLOCATION

Types of Functions :

  • malloc ( )
  • calloc( )
  • realloc ( )

Dynamic memory allocates  only  form HEAP area


Static Allocation

  • when you declare Static or global variable that reserves Block of Memory
  • Fixed Size ---     when Program loaded
  • Never Free---    Till Program gets Unloaded


Automatic Allocation

  • Stack area

Dynamic memory Allocation

  • NOT Support for C language
  • There is NO dynamic Storage Class 

 



 








Comments

Post a Comment

Popular posts from this blog

C Questions

C Questions
C Questions

Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,
Programs run under DOS environment, The underlying machine is an x86 system, Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed).
Predict the output or error(s) for the following:

void main()
{
int const * p=5; printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".
main()
{
char s[ ]="man"; int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer: mmmm
aaaa nnnn
Explanation

Zoho Interview | Set 1 (Advanced Programming Round)

Third Round: (Advanced Programming Round) Here they asked us to create a “Railway reservation system” and gave us 4 modules. The modules were:
    1. Booking
    2. Availability checking
    3. Cancellation
    4. Prepare chart
We were asked to create the modules for representing each data first and to continue with the implementation phase.

 My Solution :

#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<string.h>#include<iostream.h>#include<time.h>#include<iomanip.h>#include<fstream.h>char f[10]="f";char s[10]="s";int addr,ad,flag,f1,d,m,i,amt;float tamt; class login {public:char id[100];char pass[100];char*password;void getid(){ cout<<"Enter your id:";gets(id); password=getpass("Enter the password:");strcpy(pass,password);}void displayid(){ cout<<"Id:";puts(id); cout<<"Password:";puts(pass);}}; class detail {public:in…

Hackerrank > SQL > Basic Select

Select
01-Select All
Given a City table, whose fields are described as +-------------+----------+ | Field       | Type     | +-------------+----------+ | ID          | int(11)  | | Name        | char(35) | | CountryCode | char(3)  | | District    | char(20) | | Population  | int(11)  | +-------------+----------+
write a query that will fetch all columns for every row in the table.

My Solution
SELECT*FROM city;
---------------------------------------------------------------------------------
02-Select by ID
Given a City table, whose fields are described as