The greatest mistake you can make in life is to be continually fearing you will make one
Showing posts with label C Puzzles. Show all posts
Showing posts with label C Puzzles. Show all posts

Wednesday, 17 March 2010

C Question of the Day -malloc(),calloc(),realloc(),free()

1. Will this result in any runtime error?
#include <stdlib.h>
main()
{
int p;
p=calloc(1,sizeof(int));
free(p);
p=NULL;
free(p);
}   
Solution

No
Freeing a null pointer wont result in any error; The free() call would return without doing anything


2. Will this result in any runtime error?
#include <stdlib.h>
main()
{
int *p;
p=calloc(1,sizeof(int));
free(p);
p=realloc(p,sizeof(int));
}
Solution

Yes Error: "glibc detected ** ... : double free or corruption"
Reason: "realloc(ptr,size)" has to be invoked after (m|c)alloc(), but before free()


3. Will this result in any runtime error?

#include <stdlib.h>
main()
{
int p;
p=calloc(1,sizeof(int));
free(p);
p=NULL;
p=realloc(p,sizeof(int));
}
Solution

No
"realloc(,size)" is equivalent to "malloc(size)"

4. Will this result in any runtime error?

#include <stdlib.h>
main()
{
int *p;
p=calloc(1,sizeof(int));
free(p);
p=realloc(p, 0 * sizeof(int));
p=NULL;
p=realloc(p, 1 * sizeof(int));
*p=1;
free(p);
}
Solution

Yes. Error: "glibc detected ** ... : double free or corruption"
Reason: realloc(,0) is equivalent to free(); So we end up with double free


5.What is the output of the following program?
#include<stdio.h>
void main()
{
    int *mp,*cp;
    mp=(int*)malloc(sizeof(int));
    printf("mp=%d\n",*mp);
    cp=(int*)calloc(sizeof(int),1);
    printf("cp=%d\n",*cp);
}
Solution

mp=garbage value
cp=0
The memory space allocated by malloc is uninitialized, so mp has some garbage value. calloc initilize the allocated memory space to zero. so cp=0


6.What is the output of the following program?
#include<stdio.h>
void main()
{
    char *pd,*ps="I LOVE C";
    pd=malloc(strlen(ps));
    strcpy(pd,ps);
    printf("%s",pd);
    free(pd);
}
  1. free() fails
  2. strcpy() fails
  3. prints I LOVE C
  4. error
Solution

3.prints I LOVE C


7.What is the output of the following program?
#include<stdio.h>
void main()
{
    int *p;
    p=(int *)malloc(-10);
    printf("p=%d",*p);
    free(p);
}
Solution

Segmentation Fault


8.What is the output of the following program?
#include<stdio.h>
int main()
{
    int *p;
    p=(char *)malloc(sizeof(10));
    printf("The starting address is %d\n",p);
    return 0;
}
  1. Compilation Error
  2. Runtime Error
  3. Will give a warning,but run anyway
  4. neither warning nor error
Solution

3.Will give a warning,but run anyway
The starting address is 14311440

Tuesday, 9 March 2010

C Question of the Day -Array

1.What is the output of the following program?
#include<stdio.h>
main()
{
    char name[]="sun";
    int i;
   for(i=0;name[i];i++)
    {
        printf("%c%c%c%c\n",name[i],*(name+i),*(i+name),i[name]);
    }
    return 0;
}
Solution
ssss
uuuu
nnnn

name[i],*(name+i),*(i+name),i[name] are all different ways of expressing the array element.Here name is the base address.i is the index number


2.What is the output of the following program?
#include<stdio.h>
main()
{
    int num[]={2.3,3.4,4,5.6,7};
    int i,*x=num,*y=num;
   for(i=0;i<5;i++)
    {
        printf("%d",*num);
        ++y;
    }
    for(i=0;i<5;i++)
    {
        printf("%d",*x);
        ++x;
    }
    return 0;
}
Solution
2222223457Initially pointer num is assigned to both x and y.In the first loop the pointer y is incremented and the num value is printed.So the value 2 is printed 5 times. In the 2nd loop the pointer x is incremented and the value in x is printed. so the integer values 23457 will be printed


3.What is the output of the following program?
#include<stdio.h>
main()
{
    char str[]="Welcome";
    display(str);
    return 0;
}
void display(char *str)
{
    printf("Text=%s\n",str);
}
Solution
Compiler Error: Type mismatch in redeclaration of function display
In the main function when the function display is encountered,the compiler doesnt know anything about the function display. It assumes the arguments and return types to be integers(default). But in the actual function display the arguments and the return type contradicts with the assumption. Hence a compile time error occurs.


4.What is the memory allocated by the following definition?
[Assuming size of integer is 4 bytes]
int (*p)[10];
Solution
P is a array of 10 integer pointers. 40 bytes memory is allocated


5.What is the memory allocated by the following definition?
int (*p)(10);
Solution
P is a pointer to a function. size of a pointer is 4 bytes. So 4 bytes memory is allocated.

Friday, 5 March 2010

C Question of the Day -Preprocessor3

1.What is the output of the following program?
#include<stdio.h>
#define clrscr() 10
int main()
{
    printf("result=%d\n",clrscr());
    return 0;
}
Solution

result=10
#defines are used for textual replacement
2.What is the output of the following program?
#include<stdio.h>
#define fun(f1,f2) f1##f2
int main()
{
    int some100=100;
    printf("result=%d\n",fun(some,100));
    return 0;
}
Solution

result=100
To know about the ## operator Click here

3.What is the output of the following program?
#include<stdio.h>
#define FALSE -1
#define TRUE 1
#define NULL 0
int main()
{
    if(NULL)
        puts("NULL\n");
    else if(FALSE)
        puts("FALSE\n");
    else
        puts("TRUE\n");
    return 0;
}
Solution

FALSE
Preprocessor doesnt replace the vaues given inside the double quotes.The check by if condition is boolean value false. so it goes to else if part.-1 is boolean value true. hence it prints FALSE.
4.What is the output of the following program?
#include<stdio.h>
#define max 5
#define int arr1[max]
main()
{
    typedef char arr2[max];
    arr1 list={0,1,2,3,4};
    arr2 name="name";
    printf("%d %s\n",list[0],name);
    return 0;
}
Solution

Compier Error :arr1 undeclared
arr2 is decared of ype array of size 5 of characters.so it can be used to declare the variable name of the type arr2.But it is not the case of arr1.Hence an error.
#defines are used for textual replacement whereas typedefs are used for declaring new types.

5.What is the output of the following program?
#include<stdio.h>
#define int char
main()
{
    int i=65;
    printf("sizeof(i)=%d \n",sizeof(i));
    return 0;
}
Solution

sizeof(i)=1
#
define replaces the string int by the macro char.The size of char is 1 byte

6.What is the output of the following program?
#include<stdio.h>
#define assert(cond) if(!(cond))\
        printf("assertion failed for condition %s\n",#cond)
main()
{
    int x=100;
    if(x==100)
        assert(x<100);
    else
        printf("No assert call\n");
    return 0;
}
Solution
assertion failed for condition x<100


7.What is the output of the following program?
#include<stdio.h>
#define assert(cond) if(!(cond))\
        printf("assertion failed for condition %s\n",#cond)
main()
{
    int x=100;
    if(x==0)
        assert(x<100);
    else
        printf("No assert call\n");
    return 0;
}
Solution
No output
The else part in which the printf is there becomes the else for if in the assert macro.Hence nothing is printed.The solution is to use conditional operator instead of if statement.#define assert(cond) ((cond)?(0):printf(""))


8.What is the output of the following Program?
#include<stdio.h>
#define string_def char*
main()
{
    typedef char* string_type;
    string_type s1="My",s2="name";
    string_def s3="is",s4="Suni";
    printf("%s %s %s %s\n",s1,s2,s3,s4);
    return 0;
}
Solution
Segmentation Fault
The preprocessor output is
main()
{
    typedef char* string_type;
    string_type s1="My",s2="name";
    char* s3="is",s4="Suni";
    printf("%s %s %s %s\n",s1,s2,s3,s4);
    return 0;
}
s4 is of type char not char* so printing s4 as a string produce segmentation fault.

9.What is the output of the following program?
#include<stdio.h>
#define DEF(array,type) sizeof(array)/sizeof(type)
main()
{
    int arr[10];
    printf("Total number of array elements=%d",DEF(arr,int));
    return 0;
}
Solution
Total number of array elements=10
The size of integer array of 10 elements is 10*sizeof(int).The macro expands to sizeof(arr)/sizeof(int)=>10*sizeof(int)/sizeof(int).So the answer is 10


10.What is the output of the following Program?
#include<stdio.h>
#define max main()
main()
{
    max;
    printf("Hello Welcome\n");
    return 0;
}
  1. Compilation error
  2. Preprocessing error
  3. runtime error
  4. executes until the stack overflows
Solution
4.executes until the stack overflows

Wednesday, 3 March 2010

C Question of the Day -Preprocessor2

1.What will be printed on the screen?
#include<stdio.h>
#define x -100
int main()
{
    int x;
    #ifdef x
        printf("Hello friend\n");
    #else
        printf("Hello enemy\n");
    #endif
    return 0;
}
  1. Hello friend
  2. Hello enemy
  3. Compiler error
  4. Hello friend Hello enemy
Solution
Compiler error
The preprocessor replace int x; as int -100; so the compiler produce expected identifier error. If the statement int x; is not there then the output is Hello friend


2.What is the output of the following program?
#include<stdio.h>
#define ZERO 0
int main()
{
    #ifdef ZERO
        printf("Zero defined\n");
    #endif
    #ifndef ZERO
        printf("Zero undefined\n");
    #endif
    return 0;
}
Solution
Zero defined

3.What is the output of the following program?
#include<stdio.h>
#define ADD(X,Y) X+Y
int main()
{
    #undef ADD
    fun();
    return 0;
}
void fun()
{
    #ifndef ADD
        #define ADD(X,Y) X*Y
    #endif
    int z=ADD(3,2);
    printf("z=%d",z);
}
Solution
z=6

4.What is the output of the folowing program?
#include<stdio.h>
#define ADD(X,Y) X+Y
int main()
{
    #undef ADD
    fun();
    return 0;
}
void fun()
{
    #ifndef ADD
        #define ADD(X+Y) X*Y
    #endif
    int z=ADD(3,2);
    printf("z=%d",z);
}
 Solution
Compier error: "+" may not appear in macro parameter list

 5.What is the output of the following program?
#include<stdio.h>
#ifdef TRUE
    int X=0;
#endif
int main()
{
    int Y=1,Z=2;
    printf("X=%d,Y=%d,Z=%d\n",X,Y,Z);
    return 0;
}
Solution
Compier error: X undecared


6.What is the output of the folowing program?
#include<stdio.h>
#undef _FILE_
    #define _FILE_ "WELCOME"
int main()
{
    int Y=1,Z=2;
    printf("%s\n",_FILE_);
    return 0;
}
  1. Compilation Error
  2. Run Time Error
  3. Compiles But gives a warning
  4. Compiles Normally
Solution
4.Compies Normally.
The program compiles without error and produce output as WELCOME

7.What is the output of the following program?
#include<stdio.h>
#pragma pack(2)
struct SIZE
{
    int i;
    char ch;
    double db;
};
int main()
{
    printf("size=%d\n",sizeof(struct SIZE));
    return 0;
}
  1. 12
  2. 14
  3. 16
  4. 8
Solution

2.14
size of int 4 bytes,char 1 byte and doube 8 bytes. each member alignment take 1 byte.integer is packed to 2 bytes. so 14 bytes.
#pragma pack(2) directive would cause that member to be packed in the structure on a 2-byte boundary.If #pragma pack(2) line is not there then the output is 16.and if #pragma pack(4) is there then there is no effect.and output is same as original 16

8.What is the output of the following program?
#include<stdio.h>
#if something==0
    int some=0;
#endif
int main()
{
    int thing=0;
    printf("some=%d,thing=%d\n",some,thing);
    return 0;
}
Solution


some=0 thing=0

Monday, 1 March 2010

C Question of the Day -Preprocessor

1.What is the output of the following program?
#include<stdio.h>
#define PRODUCT(x) (x*x)
int main()
{
    int a=4,z;
    z=PRODUCT(a+1);
    printf("z=%d\n",z);
    return 0;
}
Solution


z=9
The expected output is 25. But the preprocessor replaces z=PRODUCT(4+1) as z=(4+1*4+1).* has higher preceddence than + . so the output is 4+4+1=>z=9

2.What is the output of the following program?
#include<stdio.h>
#define PRODUCT(x) (x*x)
int main()
{
    int a=4,x,y;
    x=PRODUCT(a++);
    y=PRODUCT(++a);
    printf("X=%d\t Y=%d\n",x,y);
    return 0;
}
Solution
X=16 Y=64


3.What is the output of the following program?
#include<stdio.h>
#define SEMI ;
int main()
{
    int x=4 SEMI ;
    printf("X=%d\n",x)SEMI
    return 0 SEMI
}
Solution
x=4
The program will not produce error.C statements should end with a semicolon. The compiler will take the 2nd  ; as a empty statement in line 5.


4.What is the output of the following program?
#include<stdio.h>
#define CHAR1 char
int main()
{
    typedef char CHAR2;
    CHAR1 x;
    CHAR2 y;
    x=255;
    y=255;
    printf("X=%d\tY=%d\n",x,y);
    return 0;
}
Solution
X=-1 Y=-1
default value of char is signed char.so the value above 127 are taken as the 2's complement value


5.What is the output of the following program?
#include<stdio.h>
#define SIZE sizeof(int)
int main()
{
    int i=-1;
    if(i<SIZE)
        printf("True\n");
    else
        printf("False\n");
    return 0;
}
Solution
False


6.What is the output of the following program?
#include<stdio.h>
#define SIZE(a) (&a+1) - &a
int main()
{
    float x;
    printf("X=%d\n",SIZE(x));
    return 0;
}
Solution
X=1

Wednesday, 24 February 2010

C Question of the Day -Enum

1.What is the output of the following program?
#include<stdio.h>
int main()
{
    enum measure {left=10,right,top=100,bottom};
    printf("left=%d\tright=%d\ttop=%d\tbottom=%d\n",left,right,top,bottom);
    return 0;
}

Solution
left=10 right=11 top=100 bottom=101
left is assigned to10.so next to left ie right is automatically assigned to 12.top is explicitly assigned to 100 so next to top ie bottom becomes 101

 2.What is the output of the following program?
#include<stdio.h>
int main()
{
    enum student1 {Anand=0,Ashok,Alex} Boys;
    enum student2 {skippy=0,slowvy,Ashok} Girls;
    Girls=slowvy;
    switch(Girls)
    {
        case Skippy:
            printf("Skippy\n");
            break;
        case Slowy:
            printf("Slowy\n");
            break;
        case Ashok:
            printf("Ashok\n");
            break;
        default:
            break;
    }
     return 0;
}
Solution

Compiler Error
The program is failed to compile because 'Ashok' is both in the enumeration list

3.What is the output of the following program?
#include<stdio.h>
#define FALSE 1
int main()
{
    enum Boolian{FALSE=0,TRUE};
    enum Boolian b;
    printf("False=%d\n",FALSE);
    printf("True=%d\n",TRUE);
    return 0;
}
Solution

Compiler Error
The program is failed to compile because the preprocessor will try to change the 'FALSE' to 1 in the enum statement

4.What is the output of the following program?
#include<stdio.h>
enum Boolian {FALSE=0,TRUE}b;
#define FALSE 1
int main()
{
    enum Boolian b;
    printf("False=%d\n",FALSE);
    printf("True=%d\n",TRUE);
    return 0;
}
Solution

False=1 True=1
This program will compile but the #define statement will make FALSE as 1.so FALSE and TRUE both have a value of 1

5.What is the output of the following program?
#include<stdio.h>
enum {false,true};
int main()
{
    int x=1;
    do
    {
        printf("x=%d\t",x);
        x++;
        if(x<10)
            continue;
    }while(false);
    return 0;
}
Solution
x=1

6.What is the output of the following program?
#include<stdio.h>
int main()
{
    float f=5,g=10;
    enum {i=10,j=20,k=50};
    printf("%d\n",++k);
    printf("%f\n",f<<2);
    pritf("%lf\n",f%g);
    return 0;
}
Solution

Line no 6: Error Lvalue required
Line no7: Cannot apply left shift to float
Line no8:Cannot apply mod to float
Explanation:
Enumeration constants cannot be modified, so you cannot apply ++
Bit wise operators and % operators cannot be applied on float values
7.What is the output of the following program?
#include<stdio.h>
typedef enum errorType{warning,error,exception}error;
int main()
{
    error e;
    e=1;
    printf("e=%d\n",e);
    return 0;
}
Solution
Compiler error:Multiple declaration for error
Explanation:
The name error is used in 2 places. first it is a enumeration constant with value 1.
The second one is it is a type name(due to typedef) for enum error type.The compiler cannot distinguish the meaning of error so it produce a error message

Monday, 22 February 2010

C Question of the Day 5

1.What is the output of the following program?
#include<stdio.h>
int main()
{
    int x=0,y=1;
    if(x=0)
    {
        printf("True\n");
    }
    else
    {
        printf("False\n");
    }
    return 0;
}
Solution
False
if(x=0) then x value is assigned to zero. now if(x=0) becomes if(0). The rule is if(n) becomes true when n is any positive or negative number except zero. so the condition is failed. so the else part is executed. The answer is false


2.What is the output of the following program?
#include<stdio.h>
int main()
{
    int x=1;
    x=5+5*x++;
    printf("x=%d\n",x);
    return 0;
}
Solution
x=11
When Postfix(x++) operation is used with variable in expression then the expression is evaluated first with original value then the variable is incremented.
x=5+5*1=>x=5+5=>10
now x will be incremented by one.x=10+1=>x=11


3.What is the output of the following program?
#include<stdio.h>
int main()
{
    int x=1,y;
    y=5+5*x++;
    printf("x=%d\t y=%d\n",x,y);
    return 0;
}
Solution

x=2  y=10

Saturday, 20 February 2010

C Question of the Day 4

1.What is the output of the following program?
#include<stdio.h>
int main()
{
    int a=10,b=20,c=30;
    c=a==b;
    printf("c=%d",c);
    return 0;
}
Solution
c=0
== is a relational operator.if the 2 operand is equal it returns 1(true) else return false.here a is not equal to b. so a==b returns 0. and 0 is stored in c. so the result is c=0


2.What is the output of the following program?
#include<stdio.h>
int main()
{
    int a=1,b=2;
    switch(a)
    {
        case 1:
                printf("GOOD\n");
                break;
        case b:
                printf("BAD\n");
                break;
    }
    return 0;
}
Solution
Compiler Error: case label does not reduce to an integer constant
The case statement can have only constant expressions ie we cannot use variable names directly in to a case statement. so an error happen.But enumerated types can be used in case statements

3.What is the output of the following program?
#include<stdio.h>
int main()
{
    int x;
    printf("ans=%d",scanf("%d",&x)); //value 10 is given as input here
    return 0;
}
Solution
ans=1
The scanf function returns number of items successfully read.
Here 10 is given as input which should have been scanned successfully. So number of items read is 1

C Question of the Day 3

1.What is the output of the following program?
#include<stdio.h>> 
int main()
{
    float x;
    (int)x=100;
    printf("x=%d",x);
    return 0;
}
Solution

error: lvalue required as left operand of assignment
After using any operator on operand it always return some integer value. type casting operator is also doing the same thing. so (int)x is converted in some integer value(garbage value). we cannot assign any constant value to another constant value in c.
(int)x=100==>2345332=100.
2345332 is a garbage value.
So the program results an error

2.What is the output of the following program?
#include<stdio.h>>
int main()
{
    int x;
    x=sizeof(!7.5);
    printf("x=%d",x);
    return 0;
}
Solution

x=4
! is a unary negation operator.It returns either 0 or 1.
! converts a non zero operand in to 0 and a zero operand in to a 1.
so !7.5 returns 0.since 0 is a integer number and size of integer data type is 4 bytes in a 32 bit compiler

3.What is the output of the following program?
#include<stdio.h>
int main()
{
    int x;
    x=012+0x46+20;
    printf("x=%d",x);
    return 0;
}
Solution

x=100
012 is a octal number.The decimal value of 012=1*8+2=10.
0x46 is a hexadecimal value.The decimal value of 0x46=4*16+6=70.
so the total value of x=10+70+20=100









error: lvalue required as left operand of assignment
After using any operator on operand it always return some integer value. type casting operator is also doing the same thing. so (int)x is converted in some integer value(garbage value). we cannot assign any constant value to another constant value in c.
(int)x=100==>2345332=100.
2345332 is a garbage value.
So the program results an error 

Friday, 19 February 2010

C Question of the Day 2

1.What is the output of the following program?
#include<stdio.h>>
int main()
{
    int x=100;
    printf("x=%d\nsizeof(x++)=%d\nx=%d\n",x,sizeof(x++),x);
    return 0;
}
Solution
x=100
sizeof(x++)=4
x=100
The x value is not incremented after the x++ operation.because the increment operation performed inside the sizeof operator doesn't change the value of x.
The 'sizeof' operator is used to determine the amount of space anydata-element/datatype occupies in memory


2.What is the output of the following program?
#include<stdio.h>>
int main()
{>
    int x=10;
    printf("x1=%d\n",printf("x2=%d\n",printf("x3=%d\n",x)));
    return 0;
}
Solution

x3=10
x2=6
x1=5
The output function printf returns the number of characters printed.






x=100
sizeof(x++)=4
x=100
The x value is not incremented after the x++ operation.because the increment operation performed inside the sizeof operator doesn't change the value of x.
The 'sizeof' operator is used to determine the amount of space anydata-element/datatype occupies in memory

Thursday, 18 February 2010

C Question of the Day 1

1.What is the output of the following program?
#include<stdio.h>
int main()
{
    int i=10,j=20;
    j=i++ + ++i;
    printf("%d %d",i,j);
    return 0;
}
Solution
As per C standard, there is no such rule to evaluate either right or left hand side of operator + on priority.Hence the statements like i+++++i should be avoided in programming


2.What is the output of the following program?
#include<stdio.h>
int main()
{
    float x;
    x=50/100;
    printf("x=%f",x);
    return 0;
}
Solution
x=0.000000
The expected output is 0.500000.because dividing an integer by an integer resulting a integer value. so 50/100 provide 0. but x is a float so the result is 0.000000
int/int=int
int/float=float
float/int=float
float/float=float



3. What is the output of the following program?
#include<stdio.h>
int main()
{
    int x;
    x=10,20,30;
    printf("x=%d",x);
    return 0;
}
Solution
x=10


4. What is the output of the following program?
#include<stdio.h>
int main()
{
    int a=10,b=20,c=30;
    printf("%d%d%d");
    return 0;
}
Solution
-973480632 -973480616 0
Garbage value is printed

5.What is the output of the following program?
#include<stdio.h>
int main()
{
    int x=10;
    if(!!x)
        printf("!x=%d",!x);
    else
        printf("x=%d",x);
    return 0;
}
Solution
!x=0
! is a unary negation operator.! converts a non zero operand in to 0 and a zero operand in to a 1



!x=0