Pages

Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Friday, December 15, 2017

Static variable behavior

How the static variable behaves?

#include
//int s1();
int s1()
{
  static int s;
  return s++;
}

main()
{
  int i=1;
  while (i<=2)
  {      
    i++;
    printf("S=%d\n", s1());
  }

}



Simple program. But here's the trick.
s is a static variable. 

    return s++;
the post increment is done as if:
    
    return s;
    s = s + 1;

So, when the first time s1() prints, it prints the value of s = 0, s being a static variable it's initialized to 0. But the first time s1() returns before it's being incremented. The next statement of course executes, and s is incremented. Since it's a static variable, it's not in the call stack, hence it's got incremented after the s1() function returns, but before the function actually exits.

As per Wikipedia:
When the program (executable or library) is loaded into memorystatic variables are stored in the data segment of the program's address space (if initialized), or the BSS segment (if uninitialized), and are stored in corresponding sections of object files prior to loading.

As per this 1995 Linux Journal article: http://www.linuxjournal.com/article/1059
Executable code is always placed in a section known as .text; all data variables initialized by the user are placed in a section known as .data; and uninitialized data is placed in a section known as .bss.

Hence the static variable actually increments.

Friday, May 20, 2011

Test your own C Programming skills





Hello World!

Good morning C programmers. Here is a compilation of couple of C and C++ questions to test your C/C++ programming knowledge. Most of the time you will be facing similar questions in job interviews for Software engineer or programmer not only at the fresher level but also at a very senior level. Many companies expect you to be hands on even at senior level. C is a programming language which is easy and at the same time extremely difficult if asked about complex pointer related questions. So, one has to be extremely careful in answering such questions.







Q1. Find the o/p:
main()
{
    char *ptr="hello";
    char ary[]="world";

printf("PTR: &ptr=%x, ptr=%x, *ptr=%x, ptr[0]=%x\n", &ptr,ptr, *ptr, ptr[0]);
printf("ARY: &ary=%x,ary=%x, *ary=%x, ary[0]=%x\n", &ary, ary, *ary, ary[0]);
}

Ans:


Q2. Find the o/p:
main()
{
    struct node {
        char a;
        int b; 
        short c;
        struct node next;
    }n1;   

printf("Ans1:%d\n", sizeof(n1));

return 0;
}

Ans:


Q3. Find the o/p:
main()
{
    struct node {
        char a;
        int b; 
        short c;
        struct node *next;
    }n1;   

printf("Ans1:\n\t node=%x\n \t node+2=%x\n", (char *)&n1, (char *)&n1+2);
printf("Ans2:%d\n", sizeof(n1));

return 0;
}
Ans:


Q4. What is the difference between fopen() and open()? When do you choose to use one over the other?

Ans:



Q5. Find the o/p:
main()
{
if(!printf("Hello ")){}
else
printf("World!");
}
Ans:


Q6. Find the o/p:
main()
{
struct i{
int a;    //4
double b;    //8
char * c;    //4
char d[7];    //8
short e;    //4
int f;    //4
};
printf("sizeof(i)= %d", sizeof(struct i));
}
Ans:


Q6.1. Find the o/p:
main()
{
struct i{
int a;    //4
double b;    //8
char * c;    //4
char d[3];    //4
short e;    //4
int f;    //4
};
printf("sizeof(i)= %d", sizeof(struct i));
}
Ans:



Q7. Find the o/p:
# include < stdio.h >
void main()
{
printf(NULL) ;
return ;
}
Ans:


Q8. Find the o/p:
# include < stdio.h >
void main()
{
int i = 0;
printf(i) ;
return ;
}
Ans:


Q9. Find the o/p:
#include <stdio.h>
void main()
{
printf("%s",NULL) ;
return ;
}
Ans:


Q10. Find the o/p of this last one:
main()
{
printf("%%",7);
}
Ans:


Q11. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Ans:


Q12. What is asmlinkage and what is it's use?
Ans:


Q13. What is output?
main()
{
printf("%x",-1<<4); }

Ans:

Link to the earlier post: Test your programming skills.

Enjoy yourself.
Regards,
Kongkon





Tuesday, March 08, 2011

Single Linked List using C




Here is a single linked list data structure using C Language:


#include

struct node {
        int data;
        struct node * next;
};

struct node *first = NULL;

int menu();

struct node * insert_node(int data);
struct node * delete_node(int data);
int count_node(struct node *);
int traverse_list(struct node *);


int menu()
{
int item = 0;

return item;
}

/*
* This routine will insert a new node to the left hand side of a linked list. And make this new node as the first node after insertion.
*/
struct node * insert_node(int data)
{
        struct node * temp = NULL;

        temp = (struct node *)malloc(sizeof(struct node));
        if (!temp)
                printf("Not enough memory in the system\n");

        // insert data;
        temp->data = data;

        if(first == NULL)
        {
                first = temp;
                temp->next = NULL;
                //printf("data=%d\n", temp->data);
        }
        else
        {
                temp->next = first;
                first = temp;
        }

return first;
}
/*
delete_node(int data) deletes the first node from the singly linked list where the data matches, and returns the starting of the list.
*/
struct node * delete_node(int data)
{
struct node * current = first, *prev;
//search the list for the first occurance of "data". If no node with "data" found then the list remains the same.

        while(current && current->data!=data)
        {
                prev = current;
                current=current->next;
        }
        prev->next = current->next;
        free(current);

return first;
}
int traverse_list(struct node *list_head)
{
        struct node * current, *prev;

        if (!first)
                printf("Empty list\n");

        current = first;
        prev = current->next;
        printf("\n\nList = ");
#if 1
        while(current)
        {
                printf("\t %d", current->data);
                current = current->next;
        }
#endif
        printf("\n\n");
}

main()
{
insert_node(30);
insert_node(40);
insert_node(50);
insert_node(60);
insert_node(70);
traverse_list(first);

delete_node(50);
traverse_list(first);
return 0;
}


Result of running this program:
kongkon@Linkat-Luidia:~/sea> ./a.out


List =   70      60      50      40      30



List =   70      60      40      30

Monday, June 07, 2010

C




Today we shall discuss about a simple C program.
I would like to explain the difference between array and &array address.
So, let's start by taking a live question. 
Q. Find the o/p:
main()
{
    char *ptr="hello";
    char ary[]="world";

printf("Ans:\n");
printf("PTR: &ptr=%x, ptr=%x, *ptr=%x, ptr[0]=%x\n", &ptr,ptr, *ptr, ptr[0]);
printf("ARY: &ary=%x,ary=%x, *ary=%x, ary[0]=%x\n", &ary, ary, *ary, ary[0]);
}

Ans:
PTR: &ptr=bfb86990, ptr=8048524, *ptr=68, ptr[0]=68
ARY: &ary=bfb8698a,ary=bfb8698a, *ary=77, ary[0]=77

When you look at the output of array and &array you will find that they both are same. Why? But, whereas in the case of a character pointer (not a character array), they seems to differ. Why again?

We all know that an array is like a constant pointer, and the address of the arrary is also indicated by the name of the array itself. Hence, when we mention arrary and when we mention &array they both mean the same and point to the same location. Memory allocation also happens in the same area as the starting address of the array.
But, but in case of a character pointer, prt and &ptr points to two distinct and different locations. &ptr is the place which is used by the compiler itself to store the actual data string that is pointed by ptr. &ptr points to a .rodata area inside the data segment, accessible and allocated by the compiler itself.

That is the only reason, why you get a segmentation fault while trying to modify the data pointed by the ptr character pointer.



Wednesday, June 27, 2007

Multi-threading in C in Linux




Today we shall talk about writing multi-threaded programming in C language in a Linux environment. Hope this will add value addition to all the novice, who are new to multi-threading in C, like me.

Here is my first multi-threaded C program, multi_thread1.c.

Step 1: Include these header files:
#include
#include
#include //for POSIX thread support

Step 2: The main program is here.
void *print_message_function( void *ptr );

main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;

/* Create independent threads each of which will execute function */

iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */

pthread_join( thread1, NULL);
pthread_join( thread2, NULL);

printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}

void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}

Step 3: Compile this program

[kongkon@cadbury multi]$ gcc multi_thread1.c
/tmp/ccwbBUsp.o(.text+0x39): In function `main':
: undefined reference to `pthread_create'
/tmp/ccwbBUsp.o(.text+0x52): In function `main':
: undefined reference to `pthread_create'
/tmp/ccwbBUsp.o(.text+0x65): In function `main':
: undefined reference to `pthread_join'
/tmp/ccwbBUsp.o(.text+0x75): In function `main':
: undefined reference to `pthread_join'
collect2: ld returned 1 exit status
[kongkon@cadbury multi]$

Step 4: Got error, then just compile, do not link(with the library code).

[kongkon@cadbury multi]$ gcc -c multi_thread1.c
[kongkon@cadbury multi]$

Step 5: Good, got success. Now, why is it not building? The error says that
: undefined reference to `pthread_create'
meaning, there is a problem while linking with the library. Question number 1, have you provided the PATH to the library? Question number 2, what is the name of the library?
There is no issue with the path, because otherwise it won't even compile your hello world program, which just use stdio.h. So, the problem is the compiler does not know the library name. Hence the solution is :

[kongkon@cadbury multi]$ gcc -lpthread multi_thread1.c
[kongkon@cadbury multi]$ ls
a.out multi_thread1.c
[kongkon@cadbury multi]$


Step 6: Here you go! Run the program.
[kongkon@cadbury multi]$ ./a.out
Thread 1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0
[kongkon@cadbury multi]$

Bingo!
The first multi-threaded program in C in Linux environment ran successfully.

Let's introduce a sleep function after the thread creation, and before the thread join.
Now, see the output of the ps command, and what you will find is that, there will be two copies of a.out process. What does that mean?

Saturday, March 25, 2006

C Questions: Lesson 1





Hello World!

1.
main()
{
printf("Hello World!\n");
}
>gcc 1.c
> ./a.out
Hello World!

Here is a space where I put some of my C questions collection.

2.
Here is a way to print/execute both if part and else part in an if-then-else construct.
main()
{
if(!printf("Hello ")){}
else
printf("World!");
}
>gcc 2.c
> ./a.out
Hello World!

3.
Sometime serious about how malloc works. Even if you pass the address of a member (variable) while you malloc a struct, see how free works. It can free up the space using that address also.
main()
{
struct a {
int b;
int c;
int d;
};
struct a *ptr;
ptr = (struct a *) malloc(sizeof(struct a ));
free(ptr->c);
}

4.
Here is something about address alignment. See how memory addresses are aligned in case of a struct.
main()
{
struct i{
int a;    //4
double b;    //8
char * c;    //4
char d[7];    //8
short e;    //4
int f;    //4
};
printf("sizeof(i)= %d", sizeof(struct i));
}

Ans: 4+8+4+8+4+4=32

5.
Inside into the printf function.
# include < stdio.h >
void main()
{
printf(NULL) ;
return ;
}
> ./a.out
>

6.
# include < stdio.h >
void main()
{
int i = 0;
printf(i) ;
return ;
}
Ans:

In newer gcc compiler this will not compile.
In older ones:
> ./a.out
>

But,

# include < stdio.h >
void main()
{
int i = 0;
printf("%f\n", i) ;
return ;
}
Ans:
random number like:
-0.008430
And the result of the following will be like this:

# include < stdio.h >
void main()
{
int i = 0;
printf("%f %d\n", i) ;
return ;
}
Ans:
random number like:
-0.008430   134513785
7.
#include <stdio.h>
void main()
{
printf("%s",NULL) ;
return ;
}
> ./a.out
(null)

But,

void main()
{
int i = -10;
printf("%s\n",i) ;
return ;
}
will result in "Segmentation fault" if the value of i is other than zero.

8.
This will work.
main()
{
char *a;
char b[13]="hello world";

strcpy(a,b);
printf("%s", a);
}

9.
main()
{
printf("%%",7);
}

10.
Array boundary condition behavior
main() {
int a[4]={1,2,3,4};
printf("%u %u", &a, &a+1);
}
>gcc 10.c
> ./a.out
3220829536 3220829552

11.
Again array boundary behaviour.
main() {
int a[3]={1,2,3,4};
printf("%u %u", &a, &a+1);
}

gcc 11.c
> gcc 6.c
11.c: In function `main':
11.c:2: warning: excess elements in array initializer
11.c:2: warning: (near initialization for `a')
> ./a.out
3220516784 3220516796

12.
main()
{
int i=10;
i=i++ + ++i;
printf("i=%d",i);
}
>./a.out
i=23

13. To find greatest among two numbers without using relational operator.
int main()
{
int a,b,c,d;
printf("Enter any two nos for a and b");
scanf("%d%d",&a,&b);
c=a-b;
d=b-a;
while(c && d)
{
--c;
--d;
}
if(c)
printf("b is greatest");
else
printf("a is greatest");
}

Try this...
Copyright @ Kongkon Jyoti Dutta, 2006-2011. Powered by Blogger.