Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

28
Apr

C, C++, Programming, Data Structures Quizzes

OpenAsthra introducing c, c++, programming, os, data structures quizzes
http://quiz.openasthra.com/
(note: We didn’t not upload all of our quizzes, we put some samples for now, however framework is fully functional, we will upload soon) Please submit your quizzes to [openasthra AT gamil DOT com])

Assess Your C Skills is back
You can use same authentication information (user name and password) of OpenAsthra.com for quizzes also.

Popularity: 5%

19
Apr

Man Pages

Browse Man Pages : http://manpages.openasthra.com/
Search Man Pages : http://manpages.openasthra.com/search.php/

26
Dec

C Quiz - 1

Welcome

Welcome to the OpenAsthra QuestionPatterns.
This exam contains 10 questions of which you’ll have to answer at least 7 correct to pass.
Please do not use any back button while doing this test
Please press the button below to continue to the first question.

Popularity: 24%

04
Dec

i64toa - Converts a 64 bit integer to string

Here is the program for converting a 64bit integer to string/char */ascii..
Please let me know any issues, suggestions..

 
//Converts a 64bit integer to a string
bool i64toa( int64 value, char * buf, int maxLen)
{
  int lsbByte = 0;
  char tempchr[10];
  char tmpchar;
  int count = 0;
  int bufLen = 0;
  bool negValue = false; 
  int cnt = -1;
 
  if ((buf == NULL ) || ( maxLen == 0 ))
  {
    return false;
  }
 
  memset(buf, 0, maxLen );
  memset(tempchar, 0x00, sizeof(tempchar));
 
  if( value == 0 )
  {
    buf[0] = '0';
    return true;
  }
 
  //If its a negative integer, convert it to positive and continue
  if( value < 0 )
  {
    value = -value; 
    negValue = true;
    buf[0] = '-';
    buf++;
    bufLen++;
  }
 
  //Extract byte by byte starting from the least significant byte 
  //of the 8 byte integerand form a string . The output string  
  //will contain the integer in the format least significant byte
  //to most significant byte
  while (value)
  {
    if ( bufLen++ > maxLen )
    {
      return false;
    }
 
    lsbByte = (int8)( value % 10 ) ;
    value = value/10;
 
 
    cnt = snprintf( tempchr, sizeof(tempchr),"%d", abs(lsbByte) ); 
    if ( ( cnt < 0 ) || ( cnt >= (int)sizeof(tempchr) ) )
    {
      return false;
    }
 
    strcat(buf, tempchr);
    memset(tempchar, 0x00, sizeof(tempchar));
  } 
 
  if (negValue)
  {
    bufLen--;
  }
 
  //Reverse the string to get the format most significant byte to 
  //least significant byte
  for (count = 0; (count < (bufLen/2)); count++)
  {
    if (((bufLen - count - 1) < maxLen) &&
        (count < maxLen))
    {
      tmpchar = buf[count];
      buf[count] = buf [bufLen-count-1];
      buf[bufLen-count-1] = tmpchar;
    }
    else
    {
      return false;
    }
  }
 
  return true;
}

Download the source code i64toa.txt

Popularity: 12%

02
Apr

C++ Basics - Tutorial

C++ Basics

Lesson 1 - C++ Basics
Lesson 2 - Primitive Types and Operators
Lesson 3 - Control Structures
Lesson 4 - Arrays
Lesson 5 - Pointers and Strings
Lesson 6 - Classes
Lesson 7 - Operator Overloading
Lesson 8 - Inheritance
Lesson 9 - Polymorphism
Lesson 10 - Stream IO
Lesson 11 - File Processing

download this tutorial as c++ basic tutorial

Please refer C++ Advanced Tutorial

Please contact us if you need this tutorial in any other format..

Popularity: 48%

03
Jan

How Bus Error occurs

Today while testing some program I’d encountered this problem. So i’ve digged bit more into it.

The reasons for bus error are

1)accessing unaligned memory addresses: if we are accessing a memory address which is unaligned, this can potentially raise SIGBUS signal on some systems on others this may just slowdown the reading process.

2)accessing a address out of range or non existant address: if the address we are giving is not exist in our enire hardware address range then data bus going to return with error, this will trigger SIGBUS.

3)accessing undefined address: if we try to access undefined address, this may result in segmentation fault

Here is an example which explains the above stuff….

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

void catchsig(int sig)
{
  if (sig==SIGSEGV)
  {
    printf("segmentation fault\n");
  }
  else if (sig==SIGBUS)
  {
    printf("bus error\n");
  }
}

int main(int argc, char **argv)
{

  char data[sizeof(unsigned long)];
  int *x; int y;

  signal(SIGSEGV, catchsig);
  signal(SIGBUS, catchsig);

  x = (int *)(data + 1);
  y = *x; /*causes bus error on some platforms*/

  x = (int *)0xffffffff /*lets say this address is not in our hardware*/
  y = *x; /*results bus error, as address bus returns with an error*/

  x = (int *)0×100; /*undefined address*/
  y = *x;  /*casues segmentation fault on some machines*/

  return 0;

 

[tags]bus error, SIGBUS, sigmentation fault, sigbus error, sigbus signal, bus errors[/tags]

Popularity: 5%

27
Dec

UTF8 To Unicode conversion program

  1. int UTF8ToUnicode(const unsigned char *Src, int SrcLen, WCHAR *strDest, int DestLen)
  2. {
  3.   int i=0;
  4.   int outputlen=0;
  5.  
  6.   for (i=0 ; i < SrcLen; )
  7.   {
  8.     if (outputlen >= DestLen)
  9.     {
  10.       //overflow detected
  11.       break;
  12.     }
  13.  
  14.     if ( 0xc0 <= Src[i] )
  15.     {
  16.       Dest[outputlen++] = (WCHAR) ((Src[i] & ~0xc0) << 6 | (Src[i+1] & ~0x80));
  17.       i+=2;
  18.     }
  19.     else if ( 0xe0 <= Src[i] )
  20.     {
  21.       strDest[outputlen++] =(WCHAR) (Src[i] << 12 | (Src[i+1] & 0x3f) << 6 | Src[i+2] & 0x3f);
  22.       i+=3;
  23.     }
  24.     else
  25.     {
  26.       Dest[outputlen++] = (WCHAR) Src[i];
  27.       ++i;
  28.     }
  29.   }
  30.  
  31.   Dest[outputlen] = ‘\0′;
  32.   return outputlen;
  33. }

Popularity: 11%

22
Dec

Heap Overview

An Overview of Heap Overflow

Each threads of a running program has a stack where local variables are stored. In
virtual memory space
linux all program has a .BSS (global and static uninitialized varibles) and
.DATA segment (global and static initialized varibles) along with other segments
used by malloc() and allocated with brk() - Sets the end of data segment to the
values specified or mmap() - map file into memory, it ask length bytes
starting at offset from the file specified by the file descriptor fd into
memory, preferably at address start.

malloc() breaks up a chunk of memory allocated using brk() into small parts and
gives the user one of those part when a request is made.
It used various
techniques like smallest-first, best-fit, next best fit, first-fit etc.
Lot
of meta-data about the location of the chunks, ths size of the chunks and other
special area for small parts.
All these is information are organized into
buckets and in some others into balanced tree structure.

So like stack
overflow we can overflow heap also, by overwriting those meta-data.

One such vulenrable program is cprog1.c

[highlight lang=”CPP”]
#define BLOCKSIZE 666
int main(int argc, char *argv[])
{
char *pcBuf1, *pcBuf2;
pcBuf1 = (char *) malloc (BLOCKSIZE);
pcBuf2 = (char *) malloc (BLOCKSIZE);
printf(”Buffer 1: %p Buffer 2: %pn”,pcBuf1,pcBuf2)
strcpy(pcBuf1,argv[1]);
free(pcBuf2);
free(pcBuf1);
}
[/highlight]

$> gcc -o cprog1 cprog1.c
$> ./cprog1
Buffer1: 0×9017008 Buffer2: 0×90172a8***glibc detected *** double free or corruption (out): 0×90172a8 ***Aborted

Here we are overflowing

Buffer2 with the data in

argv[1]

.
malloc implementations, including Linux’s dlmalloc, store
extra information in a free chunk. As free chunks can be used to store
information about other chunks.

Note: The output of all the programs
discussed here will be complier/platform dependent.

Instead of malloc we
could have used something like

p = (char *) sbrk(BLOCKSIZE);

But it isn’t efficient,
portable. What about free?

Allocation Algorithms :

Following are some of the memory allocation
algorithms used.

  • First Fit
    • Keep a linked list of free node
    • Search for the first one that’s BIG enough
  • Best Fit
    • Keep a linked list of free node
    • Search for the smallest one that’s BIG enough
  • Free list: A circular list

[tags] heap usage, heap, heap overview, heap information, new malloc heap[/tags]

Popularity: 7%

11
Dec

Advanced Test in C: The 0×0A Best Questions for C Programmers

Using this Test In the entire test following convention are used

  • In all program, assume that the required header file/files has /have been included

Consider the data type

  • char is 1 byte
  • int is 2 byte
  • long int 4 byte
  • float is 4 byet
  • double is 8 byte
  • long double is 10 byte
  • pointer is 2 byte

1. Consider the following program:

#include
static jmp_buf  buf;

main()
{
volatile  int b;
b =3;

if(setjmp(buf)!=0)
{
printf("%d ", b);
exit(0);
}
b=5;
longjmp(buf , 1);
}

The output for this program is:

(a) 3
(b) 5
(c) 0
(d) None of the above

2. Consider the following program:

main()
{
struct node
{
int a;
int b;
int c;
};
struct node  s= { 3, 5,6 };
struct node *pt = &s;
printf("%d" ,  *(int*)pt);
}

The output for this program is:
(a) 3
(b) 5
(c) 6
(d) 7

3. Consider the following code segment:

int  foo ( int x , int  n)
{
int val;
val =1;

if (n>0)
{
if (n%2 == 1)  val = val *x;

val = val * foo(x*x , n/2);
}
return val;
}

What function of x and n is compute by this code segment?

(a) xn
(b) x*n
(c) nx
(d) None of the above

4. Consider the following program:

main()
{
int  a[5] = {1,2,3,4,5};
int *ptr =  (int*)(&a+1);

printf("%d %d" , *(a+1), *(ptr-1) );

}

The output for this program is:

(a) 2 2
(b) 2 1
(c) 2 5
(d) None of the above

5. Consider the following program:

void foo(int [][3] );

main()
{
int a [3][3]= { { 1,2,3} , { 4,5,6},{7,8,9}};
foo(a);
printf("%d" , a[2][1]);
}

void foo( int b[][3])
{
++ b;
b[1][1] =9;
}

The output for this program is:

(a) 8
(b) 9
(c) 7
(d) None of the above

6. Consider the following program:

main()
{
int a, b,c, d;
a=3;
b=5;
c=a,b;
d=(a,b);

printf("c=%d" ,c);
printf("d=%d" ,d);

}

The output for this program is:

(a) c=3 d=3
(b) c=5 d=3
(c) c=3 d=5
(d) c=5 d=5

7. Consider the following program:

main()
{
int a[][3] = { 1,2,3 ,4,5,6};
int (*ptr)[3] =a;

printf("%d %d "  ,(*ptr)[1], (*ptr)[2] );

++ptr;
printf("%d %d"  ,(*ptr)[1], (*ptr)[2] );
}

The output for this program is:

(a) 2 3 5 6
(b) 2 3 4 5
(c) 4 5 0 0
(d) None of the above

8. Consider following function

int *f1(void)
{
int x =10;
return(&x);
}

int *f2(void)
{
int*ptr;
*ptr =10;
return ptr;
}

int *f3(void)
{
int *ptr;
ptr=(int*) malloc(sizeof(int));
return ptr;
}

Which of the above three functions are likely to cause problem with pointers

(a) Only f3
(b) Only f1 and f3
(c) Only f1 and f2
(d) f1 , f2 ,f3

9. Consider the following program:

main()
{
int i=3;
int j;

j = sizeof(++i+ ++i);

printf("i=%d j=%d", i ,j);
}

The output for this program is:

(a) i=4 j=2
(b) i=3 j=2
(c) i=3 j=4
(d) i=3 j=6

10. Consider the following program:

void f1(int *, int);
void f2(int *, int);
void(*p[2]) ( int *, int);

main()
{
int a;
int b;

p[0] = f1;
p[1] = f2;
a=3;
b=5;

p[0](&a , b);
printf("%dt %dt" , a ,b);

p[1](&a , b);
printf("%dt %dt" , a ,b);
}

void f1( int* p , int q)
{
int tmp;
tmp =*p;
*p = q;
q= tmp;
}

void f2( int* p , int q)
{
int tmp;
tmp =*p;
*p = q;
q= tmp;
}

The output for this program is:

(a) 5 5 5 5
(b) 3 5 3 5
(c) 5 3 5 3
(d) 3 3 3 3

11. Consider the following program:

void e(int );

main()
{
int a;
a=3;
e(a);
}

void e(int n)
{
if(n>0)
{
e(--n);
printf("%d" , n);
e(--n);
}
}

The output for this program is:

(a) 0 1 2 0
(b) 0 1 2 1
(c) 1 2 0 1
(d) 0 2 1 1

12. Consider following declaration

typedef int (*test) ( float * , float*)
test tmp;

type of tmp is

(a) Pointer to function of having two arguments that is pointer to float
(b) int
(c) Pointer to function having two argument that is pointer to float and return int
(d) None of the above

13. Consider the following program:

main()
{
char *p;
char buf[10] ={ 1,2,3,4,5,6,9,8};
p = (buf+1)[5];
printf("%d" , p);
}

The output for this program is:

(a) 5
(b) 6
(c) 9
(d) None of the above

14. Consider the following program:

Void f(char**);

main()
{
char * argv[] = { "ab" ,"cd" , "ef" ,"gh", "ij" ,"kl" };
f( argv );
}

void f( char **p )
{
char* t;

t= (p+= sizeof(int))[-1];

printf( "%s" , t);
}

The output for this program is:

(a) ab
(b) cd
(c) ef
(d) gh

15. Consider the following program:

#include
int ripple ( int , ...);

main()
{
int num;
num = ripple ( 3, 5,7);
printf( " %d" , num);
}

int ripple (int n, ...)
{
int i , j;
int k;
va_list p;

k= 0;
j = 1;
va_start( p , n);

for (; j

The output for this program is:

(a) 7
(b) 6
(c) 5
(d) 3

16. Consider the following program:

int counter (int i)
{
static int count =0;
count = count +i;
return (count );
}
main()
{
int i , j;

for (i=0; i <=5; i++)
j = counter(i);
}

The value of j at the end of the execution of the this program is:

(a) 10
(b) 15
(c) 6
(d) 7

Answer With Detailed Explanation

_____________________________________________________________

Answer 1.

The answer is (b)

volatile variable isn’t affected by the optimization. Its value after the longjump is the last value variable assumed.

b last value is 5 hence 5 is printed.

setjmp : Sets up for nonlocal goto /* setjmp.h*/

Stores context information such as register values so that the lomgjmp function can return control to the

statement following the one calling setjmp.Returns 0 when it is initially called.

Lonjjmp: longjmp Performs nonlocal goto /* setjmp.h*/

Transfers control to the statement where the call to setjmp (which initialized buf) was made. Execution continues

at this point as if longjmp cannot return the value 0.A nonvolatile automatic variable might be changed by a call

to longjmp.When you use setjmp and longjmp, the only automatic variables guaranteed to remain valid are those

declared volatile.

Note: Test program without volatile qualifier (result may very)

Answer 2.

The answer is (a)

The members of structures have address in increasing order of their declaration. If a pointer to a structure is cast

to the type of a pointer to its first member, the result refers to the first member.

Answer 3.

The answer is (a)

Non recursive version of the program

int  what ( int x , int  n)
{
int val;
int product;
product =1;
val =x;

while(n>0)
{
if (n%2 == 1)
product = product*val;
n = n/2;
val = val* val;
}
}

/* Code raise a number (x) to a large power (n) using binary doubling strategy */
Algorithm description

(while n>0)
{
if  next most significant binary digit of  n( power)  is one
then multiply accumulated product by current val  ,
reduce n(power)  sequence by a factor of two using integer division .
get next val by multiply current value of itself
}

Answer 4.

The answer is (c)

type of a is array of int
type of &a is pointer to array of int
Taking a pointer to the element one beyond the end of an array is sure to work.

Answer 5.

The answer is (b)

Answer 6.

The answer is (c)

The comma separates the elements of a function argument list. The comma is also used as an operator in comma expressions. Mixing the two uses of comma is legal, but you must use parentheses to distinguish them. the left

operand E1 is evaluated as a void expression, then E2 is evaluated to give the result and type of the comma expression. By recursion, the expression

E1, E2, …, En

results in the left-to-right evaluation of each Ei, with the value and type of En giving the result of the whole expression.

c=a,b;  / *yields c=a* /
d=(a,b); /* d =b  */

Answer 7.

The answer is (a)

/* ptr is pointer to array of 3 int */

Answer 8.

The answer is (c)

f1 and f2 return address of local variable ,when function exit local variable disappeared

Answer 9.

The answer is (b)

sizeof operator gives the number of bytes required to store an object of the type of its operand . The operands

is either an expression, which is not evaluated ( (++i + ++ i ) is not evaluated so i remain 3 and j is sizeof int that is 2) or a parenthesized type name.

Answer 10.

The answer is (a)

void(*p[2]) ( int *, int);
define array of pointer to function accept two argument that is pointer to int and return int. p[0] = f1; p[1] = f2

contain address of function .function name without parenthesis represent address of function Value and address

of variable is passed to function only argument that is effected is a (address is passed). Because of call by value f1,

f2 can not effect b

Answer 11.

The answer is (a)

Answer 12.

The answer is (c)

C provide a facility called typedef for creating new data type names, for example declaration

typedef char string

Makes the name string a synonym for int .The type string can be used in declaration, cast, etc, exactly the same way

that the type int can be. Notice that the type being declared in a typedef appears in the position of a variable name not after the word typedef.

Answer 13.

The answer is (c)

If the type of an expression is “array of T” for some type T, then the value of the expression is a pointer to the

first object in the array, and the type of the expression is altered to “pointer to T”
So (buf+1)[5] is equvalent to *(buf +6) or buf[6]

Answer 14.

The answer is (b)

p+=sizeof(int) point to argv[2]

(p+=sizeof(int))[-1] points to argv[1]

Answer 15.

The answer is (c)

When we call ripple value of the first argument passed to ripple is collected in the n that is 3. va_start initialize p

to point to first unnamed argument that is 5 (first argument).Each call of va_arg return an argument and step p to

the next argument. va_arg uses a type name to determine what type to return and how big a step to take Consider inner loop

(; i; i&=i-1) k++ /* count number of  1 bit in i *

in five number of 1 bits is (101) 2
in seven number of 1 bits is (111) 3
hence k return 5

example

let  i= 9 = 1001
i-1  = 1000
(i-1) +1 = i
1000
+1
1 001

The right most 1 bit of i has corresponding 0 bit in i-1 this way i & i-1, in a two complement number system

will delete the right most 1 bit I(repeat until I become 0 gives number of 1 bits)

Answer 16.

The answer is (b)

Static variable count remain in existence rather than coming and going each time function is called
so first call counter(0) count =0
second call counter(1) count = 0+1;
third call counter(2) count = 1+2; /* count = count +i */
fourth call counter(3) count = 3+3;
fifth call counter(4) count = 6+4;
sixth call counter(5) count = 10+5;
_____________________________________________________________

source: My Friend Ashok Pathak posted this for other forums earlier, on my request he sent this article to me.

[tags]advanced c test[/tags]

Popularity: 6%

Next Page »