You are on page 1of 18


Free eBook
Start Here

12 Interesting C Interview Questions and
by Himanshu Arora on August 17, 2012



Tw eet


In this article, we will discuss some interesting problems on C language that can help students to brush up their C
programming skills and help them prepare their C fundamentals for interviews.

1. gets() function
Question: There is a hidden problem with the following code. Can you detect it?
int main(void)
char buff[10];
printf("\n The buffer entered is [%s]\n",buff);
return 0;

Answer: The hidden problem with the code above is the use of the function gets(). This function accepts a string
from stdin without checking the capacity of buffer in which it copies the value. This may well result in buffer
overflow. The standard function fgets() is advisable to use in these cases.

2. strcpy() function

Can you break it without knowing the password? #include<stdio. char *argv[]) { int flag = 0. To avoid these kind of problems the function strncpy() should be used. memset(passwd.sizeof(passwd)). passwd)) { flag = 1. } else { printf("\n Incorrect passwd \n"). Note from author : These days the compilers internally detect the possibility of stack smashing and so they store variables on stack in such a way that stack smashing becomes very difficult.Question: Following is the code for very basic password protection. The authentication logic in above password protector code can be compromised by exploiting the loophole of strcpy() function. } return 0.0. argv[1]). char passwd[10]. So if a user supplies a random password of such a length that causes buffer overflow and overwrites the memory location containing the default value ’0′ of the ‘flag’ variable then even if the password matching condition fails. For example : $ . strcpy(passwd. . } Answer: Yes. if(0 == strcmp("LinuxGeek". In my case also. the check of flag being non-zero becomes true and hence the password protection is breached. } if(flag) { printf("\n Password cracked \n").h> int main(int argc./psswd aaaaaaaaaaaaa Password cracked So you can see that though the password supplied in the above example is not correct but still it breached the password security through buffer overflow. This function copies the password supplied by user to the ‘passwd’ buffer without checking whether the length of password supplied can be accommodated by the ‘passwd’ buffer or not. the gcc does this by default so I had to use the the compile option ‘-fno-stack-protector’ to reproduce the above scenario.

Return type of main() should be ‘int’ rather than ‘void’. } else { // Do some processing free(ptr). Return type of main() Question: Will the following code compile? If yes.h> void main(void) { char *ptr = (char*)malloc(10). if(NULL == ptr) { printf("\n Malloc failed \n"). This is because the ‘int’ return type lets the program to return a status value. Memory Leak Question: Will the following code result in memory leak? #include<stdio. then is there any other problem with this code? #include<stdio.h> void main(void) { char *ptr = (char*)malloc(10). Though the above code is not freeing up the memory allocated to ‘ptr’ but still this would not . } return. This becomes important especially when the program is being run as a part of a script which relies on the success of the program execution. return. } Answer: The code will compile error free but with a warning (by most compilers) regarding the return type of main()function. return. } Answer: Well.3. } else { // Do some processing } return. if(NULL == ptr) { printf("\n Malloc failed \n"). 4.

Since the program terminates so all the memory allocated by the program is automatically freed as part of cleanup. } else if(argc == 1) { printf("\n Usage \n"). The free() function Question: The following program seg-faults (crashes) when user supplies input as ‘freeze’ while it works fine with input ‘zebra’. char *argv[]) { char *ptr = (char*)malloc(10). return -1. Note : If you want to know more on memory leaks and the tool that can detect memory leaks. while(*ptr != 'z') { if(*ptr == '') break. strncpy(ptr. if(NULL == ptr) { printf("\n Malloc failed \n").cause a memory leak as after the processing is done the program exits. } Answer: The problem here is that the code changes the address in ‘ptr’ (by incrementing the ‘ptr’) inside the . else ptr++. 0. } if(*ptr == 'z') { printf("\n String contains 'z'\n"). // Do some more processing } free(ptr). But if the above code was all inside a while loop then this would have caused serious memory leaks.h> int main(int argc. 9). } return 0. 10). read our article on Valgrind. Why? #include<stdio. } else { memset(ptr. 5. argv[1].

void* and C structures Question: Can you design a function that can accept any type of argument and returns an integer? Also. * and ++ operators Question: What would be the output of the following code and why? #include<stdio.while loop. atexit with _exit Question: In the code below. for(. But in case of ‘freeze’ the address held by ptr is updated inside the while loop and hence incorrect address is passed to free() which causes the seg-fault or crash. } Answer: This behavior is due to the use of function _exit().i<0xffffff. 7. return. the while loop terminates before executing even once and so the argument passed to free() is the same address as given by malloc(). 8.h> int main(void) { .i++). Now when ‘zebra’ is supplied as input. the atexit() function is not being called.h> void func(void) { printf("\n Cleanup function called \n"). _exit(0). If atexit() is required to be called then exit() or ‘return’ should be used. is there a way in which more than one arguments can be passed to it? Answer: A function that can accept any type of argument looks like : int func(void *ptr) if more than one argument needs to be passed to this function then this function could be called with a structure object where-in the structure members can be populated with the arguments that need to be passed. 6. Can you tell why? #include<stdio. } int main(void) { int i = 0. atexit(func). This function does not call the clean-up functions like atexit() etc.

return 0.0. 10.char *ptr = "Linux". memset(buff. strncpy(buff. printf("\n [%s] \n". } Answer: The output of the above would be : [L] [i] Since the priority of both ‘++’ and ‘*’ are same so processing of ‘*ptr++’ takes place from right to left. } Answer: This is because.sizeof(buff)).h> int main(int argc. Making changes in Code(or read-only) segment Question: The following code seg-faults (crashes). through *ptr = ‘T’. ptr).h> int main(void) { char *ptr = "Linux". This operation is invalid and hence causes a seg-fault or a crash. *ptr = 'T'. the code is trying to change the first byte of the string ‘Linux’ kept in the code (or the read-only) segment in the memory. argv[0]. return 0. Can you tell the reason why? #include<stdio. char *argv[]) { int i = 0.*ptr++). Going by this logic. 9. sizeof(buff)). . char buff[100].*ptr). printf("\n [%c] \n". Now since a post fix ‘++’ was applied on ptr so the next printf() would print ‘i’. ptr++ is evaluated first and then *ptr. printf("\n [%c] \n". So both these operations result in ‘L’. Process that changes its own name Question: Can you write a program that changes its own name when run? Answer: Following piece of code tries to do the required : #include<stdio.

a++.%d. printf("\n %d. return 0. Since the life time of this local variable is that of the function ‘inc()’ so after inc() is done with its processing. 7). (c = c*2)). } int main(void) { int a = 10. This can be avoided by passing the address of variable ‘a’ from main() and then inside changes can be made to the value kept at this address. "NewName". strncpy(argv[0].. } Answer: Though the above program may run perfectly fine at times but there is a serious loophole in the function ‘inc()’. (b = b*2).%d \n".h> int* inc(int val) { int a = val.i<0xffffffff. *val). b = 20. Check the process // name at this point. 12. This function returns the address of a local variable. using the address of its local variable can cause undesired results. } 11. . Returning address of local variable Question: Is there any problem with the following code?If yes. return 0. for(. int *val = inc(a).i++). // Simulate a wait.h> int main(void) { int a = 10.0. return 0.memset(argv[0].. return &a. printf("\n Incremented value is equal to [%d] \n". c = 30. a+b+c.strlen(buff)). Processing printf() arguments Question: What would be the output of the following code? #include<stdio. then how it can be rectified? #include<stdio.

. 74 Tw eet 93 Like 50 > Add your comment Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. you could be spending lot of time trying to perform even the basic administrative tasks..60 This is because the arguments to the function are processed from right to left but are printed from left to right. you might also like. 50 Linux Sysadmin Tutorials 2.40. 1. Get the Linux Sysadmin Course Now! If you enjoyed this article. Mommy. The focus of this course is to help you understand system administration tools.. Linux 101 Hacks 2nd Edition eBook Awk Introduction – 7 Awk Print Examples Advanced Sed Substitution Examples 8 Essential Vim Editor Navigation Fundamentals 25 Most Frequently Used Linux IPTables Rules Examples Turbocharge PuTTY with 12 Powerful AddOns . I found it! – 15 Practical Linux Find Command Examples 5. Top 25 Best Linux Performance Monitoring and Debugging Tools 4. 50 Most Frequently Used Linux Commands (With Examples) 3.} Answer: The output of the above code would be : 110. which will help you to become an effective Linux system administrator. If you don’t know what these tools are and how to use them.

If you know your machine and compiler you can re-order your variables to make the order such that this couldn’t happen. that C has plenty of rope to hang yourself. Wilborn . as I’m sure you do. such as the example of over writing of a variable is often the most spoken about way to hang yourself. but this time it seems you have relied on sloppy coding practices and not the standard goofs people make in the C language. Better still. make the if one that has an else and set the flag there. which is misleading because C does not specify how many variables are stored or how they are operated on.{ 20 comments… read them below or add one } 1 Jack Wilborn August 17. One. Believe me. is this what you intended or is it something in my browser or just a typo? I tell most students that try to increment anything in various areas of if or while statements that the best way is the K&R intended was to use the proper for or do while that has the option of incrementing the variable at the proper place to handle all situations. Please keep up the good work. but as a ‘C’ instructor for many years I think I should point out that C is machine independent. where as the PC’s are rather sloppy and inconsistent along with absolutely wrong in versions that I have exposed during my tenure in teaching and in actual programming. if you just help people with a good coding practice basic rules to help them avoid these pitfalls. The IBM 370 has such a feature and is wisely used in their code generation of C. Also. like your articles. 2012 at 10:06 am Hi. but also lets you do things you cannot do in other languages. A good point that many outside of programmers don’t realize that is also impacting the malware group is that of a Data Segment to prevent executing of code that is actually data. Also your example of the pointer post incrementing executes exactly how you would expect it and your explanation was difficult and not needed. and I’m sure you can find better examples to show people that this time. since some machines may do it much more efficiently another way. Jack k. I have to admit you usually have a lot of good suggestions. this would guarantee that it operates properly. You also have multiple entries of “include “.

wikipedia..please read the first paragraph. But c guarantees that the arguments should get evaluated before the function is called. 2012 at 1:25 pm 1. 2012 at 12:56 pm For all those who believe that the examples are sloppy or not professionaly Gcc follows cdecl calling convention in which arguments are evaluated from right to left .Making changes in Code(or read-only) segment: The example program given for this is trying to modify a constant string literal. 2. 2012 at 3:33 am hi. I prefer the pearl and python in Linux environment. These are definitely for a test at the end of a first Programming in C class. As a medical student.Please write me if you feel like it. Processing printf() arguments : In C language the Order in which the function arguments are evaluated is not specified . It means that the program whether produce segfault or not depends on the environment where it is running. I’ve never used memset() is any program the last 15 yrs programming and leaving variables uninitialized is a noob mistake.. Sure. That is implementation defined . 2012 at 10:30 am Professional code doesn’t look like these samples. Pros use other techniques to avoid most of these constructs completely. To know more about calling convention the below link can be referred: http://en. The goal is to have your program break ASAP in the development cycle. 2 JohnP August 17.. 6 Yuvaraj A August 21. thanks a lot i sent this article to my “C” course students 5 Ethan August 18. There are many calling conventions . As an example. not ever in front of a customer. lots of people do this because they incorrectly believe it is a waste of effort.this article is aimed to explain basic stuff to newbies with easy to understand examples… 4 jalal hajigholamali August 18. IMHO. According to the c standard the behavior of modifying constant string literal is undefined . 3 Himanshu Arora August 17.this article is not for experienced professionals. 2012 at 5:18 am I’ve never made my mind to touch the devel C language. .

printf(“\n %d. instead of . int flag = 0. The behavior is entirely compiler-specific. (b = b*2)..%d.. and could easily print out any of: “60... and the C standard makes no guarantee as to the expected behavior.40. GCC happens to do right-to-left evaluation on most platforms. Clang does left-to-right evaluation.40. 2012 at 4:31 am alistra@bialobrewy ~ % cat 1. “90.60 8 Aleksei Kozadaev August 29. If the same code runs in embedded environment where there is no concepts of segments then that statement simply overwrites that memory and the program runs fine.40.. 2012 at 7:41 pm 12 is wrong...out 60.60″. (c = c*2)).For example if runs in Linux environment it will produce segfault since it is overwriting Read only segment .40. 2012 at 12:34 am I guess the question 2 about “password crack” can also be corrected by declaring the variables as follows: char passwd[10]. return 0. 2012 at 10:27 am I believe the answer 12 is not exactly correct.. “80..c #include int main(void) { int a = 10. and some will. Any compiler is free to handle the arguments in any order. c = 30.60″. a+b+c.c alistra@bialobrewy ~ % . (Yuvaraj A +1) It would be platform/compiler dependant. or “110. Aleksei and Alistra correctly point this out..60″. 9 Charles Banas August 29. 10 Zishan Shaikh August 31.%d \n”.. I would prefer thinking of the function argument evaluation order as undefined and avoid the code like the one in the question. } alistra@bialobrewy ~ % clang 1.40.60″. 7 Alistra August 29. b = 20./a.. It’s specifically called out as undefined behavior.

IMHO. . 2012 at 3:14 am In the 5th question. if(*ptr == ”) should be if(*ptr == ”) // backslash and zero Most likely. In the original way mentioned. or char *passwd = calloc(10. char passwd[10]. 11 Mohammed Abdelkhaliq September 2. your blogging software removed the terminating null (backslash and zero) for security reasons. Something like char passwd[10] = { 0 }. flag gets allocated after passwd (genuine stack behavior i guess). the code will work just fine displaying “incorrect password”. 2012 at 5:00 am JohnP: I couldn’t agree more. lenghty passwd. By declaring “flag” after “passwd”. 2012 at 7:11 am About Question#10: Process that changes its own name Are you sure this will change the process name or just a command line argument copy of process name? Very tricky!! I am practicing C from many years but you made me also think a bit on your solution. and it’s not special for main function 12 Peter September 3. flag will be allocated memory before passwd in the stack. by changing declaration order as mentioned. So even if you overflow the buffer with flag = 0. This way there will be no memory over write or anything. 2012 at 1:56 pm regarding Q3. like: char *ptr = (char*)malloc(10). They could have used better C facilities to initialize memory/arrays. 13 Aleksei Kozadaev September 3. 14 Ganesh Shinde December 26. –> char *ptr = malloc(10 * sizeof(*ptr)). It would be more accurate if we should it’s the default return type of any [undeclared function] is int. I just confirmed this by printing their addresses. IMHO: Casting malloc (like (char*)malloc…) is a bad idea because it would hide compile-time warnings (if any) while not gaining anything. sizeof(*passwd)).

char *argv[]) { int i = 0. . } // Simulate a wait. memset(argv[0].i++)sleep(1). #include #include int main(int argc. return 1. return 0. with 'ps' you won't notice the process's name changed. “NewName”)) { printf(“unable to change process name”). 1. Only "ps -f" you can. Check the process name at this point. i am seeking the answer of this question from so long. but just wanted to point out that sometimes there is more than one solution.Process name can be changed but not this way. if (prctl(PR_SET_NAME. for(. #9 is actually perfectly okay. 15 Pramod Yadav January 5. if you know. how we can work with alt. you might not see the process in another terminal(maybe my x86 Lubuntu box's problem). I know that this isn’t a tutorial on encryption. since the password is stored in cleartext. if someone know then please tell me… 16 Mike Yue February 21.doesn’t matter lenght the original executable). I am surprise how could nobody challenges this. 17 Robert Sun March 12. 2013 at 11:09 am Ex. No crash at all. The new name should be shorter. 18 Ken Robb April 23. 2013 at 3:37 pm Another solution to #2 is to look at the text strings in the executable. 3. The string “Tinux” was printed successfully.0. } The original post solution have some limits.i<1000. ctrl and window key. 2013 at 1:52 am please tell me. 2013 at 1:24 am To Ganesh about Question#10: Following code can change process’s name(up to 16 bytes. 2.strlen(argv[0])).

and inc() . in this case it will first return the address of a to main function it exist from the function. Hence for the first print statement. 2014 at 9:54 pm The output of 8 is correct. 20 Nachiket P February 11. 2013 at 12:40 am 11th question looks no problem.5 l$ L t$(L |$0H LinuxGeek Password cracked Incorrect passwd 19 vamshi August 7.2 __gmon_start__ libc.You could use the “strings” command as follows: $ strings pw-hack /lib64/ld-linux-x86-64. The post-fix operator has higher precedence than indirection. the incrementing of ptr happens as a post-side effect and will take place just before the next print statement.6 strcpy puts __libc_start_main GLIBC_2. But by definition of stack is used to store function variables before processing new function. Leave a Comment Name E-mail Website .so. when we call a function ( jump to a new function) . value printed is still *ptr which is [L]. But it is not because ‘++’ and ‘*’ have same precedence.2.

Master the Tools.055 people like The Geek Stuff.Monitor Everything.Practical Examples to Build a Strong Foundation in Linux Bash 101 Hacks eBook .Take Control of Your Bash Command Line and Shell Scripting Sed and Awk 101 Hacks eBook . Facebook social plugin POPULAR POSTS 12 Amazing and Essential Linux Books To Enrich Your Brain and Library 50 UNIX / Linux Sysadmin Tutorials 50 Most Frequently Used UNIX / Linux Commands (With Examples) . Be Proactive.Enhance Your UNIX / Linux Life with Sed and Awk Vim 101 Hacks eBook . Configure it Right. and Sleep Well The Geek Stuff Like 6.Notify me of followup comments via e-mail Submit Previous post: How to Log Linux IPTables Firewall Dropped Packets to a Log File Next post: Linux OD Command Examples (Octal Dump) RSS | Email | Twitter | Facebook | Google+ Search COURSE Linux Sysadmin CentOS 6 Course . and be Lazy EBOOKS Linux 101 Hacks 2nd Edition eBook .Practical Examples for Becoming Fast and Productive in Vim Editor Nagios Core 3 eBook .

I found it! -.15 Practical Linux Find Command Examples 15 Awesome Gmail Tips and Tricks 15 Awesome Google Search Tips and Tricks RAID 0. RAID 10 Explained with Diagrams Can You Top This? 15 Practical Linux Top Command Examples Top 5 Best System Monitoring Tools Top 5 Best Linux OS Distributions How To Monitor Remote Linux Host using Nagios 3.How To Be Productive and Get Things Done Using GTD 30 Things To Do When you are Bored and have a Computer Linux Directory Structure (File System Structure) Explained with Examples Linux Crontab: 15 Awesome Cron Job Examples Get a Grip on the Grep! – 15 Practical Grep Command Examples Unix LS Command: 15 Practical Examples 15 Examples To Master Linux Command Line History Top 10 Open Source Bug Tracking System Vi and Vim Macro Tutorial: How To Record and Play Mommy. RAID 5.0 Awk Introduction Tutorial – 7 Awk Print Examples How to Backup Linux? 15 rsync Command Examples The Ultimate Wget Download Guide With 15 Awesome Examples Top 5 Best Linux Text Editors Packet Analyzer: 15 TCPDUMP Command Examples The Ultimate Bash Array Tutorial with 15 Examples 3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id Unix Sed Tutorial: Advanced Sed Substitution Examples UNIX / Linux: 10 Netstat Command Examples The Ultimate Guide for Creating Strong Passwords 6 Steps to Secure Your Home Wireless Network Turbocharge PuTTY with 12 Powerful Add-Ons CATEGORIES Linux Tutorials Vim Editor Sed Scripting Awk Scripting Bash Shell Scripting Nagios Monitoring OpenSSH IPTables Firewall Apache Web Server MySQL Database Perl Programming Google Tutorials Ubuntu Tutorials . RAID 1.

how-to.PostgreSQL DB Hello World Examples C Programming C++ Programming DELL Server Tutorials Oracle Database VMware Tutorials Ramesh Natarajan Follow About The Geek Stuff My name is Ramesh Natarajan. Bash 101 Hacks eBook Sed and Awk 101 Hacks eBook Vim 101 Hacks eBook Nagios Core 3 eBook Contact Us Email Me : Use this Contact Form to get in touch me with your comments. My focus is to write articles that will either teach you or help you resolve a problem. Read more about Ramesh Natarajan and the blog. You can also simply drop me a line to say hello!. security and web. troubleshooting tips and tricks on Linux. questions or suggestions about this site. database. hardware. . Support Us Support this blog by purchasing one of my ebooks. I will be posting instruction guides.

Follow us on Google+ Follow us on Twitter Become a fan on Facebook Copyright © 2008–2014 Ramesh Natarajan. All rights reserved | Terms of Service .