12 C language interview questions

Source: Internet
Author: User

Statement: This article is reprinted. I didn't have time to read it, but I only read it a little. I saved it for convenience. Now I can't find the original website at the time, sorry.

1. Gets () function

Q: Please find out the problem in the following code:

# Include <stdio. h>
Int main (void)
{
Char buff [10];
Memset (buff, 0, sizeof (buff ));
 
Gets (buff );
 
Printf ("\ n the buffer entered is [% s] \ n", buff );
 
Return 0;
}
A: The problem in the code above lies in the use of the function gets (). This function receives a string from stdin without checking the cache volume it copies, which may cause cache overflow. We recommend that you use the standard function fgets.

2. strcpy () function

Q: The following is a simple password protection function. Can you crack the password without knowing it?

# Include <stdio. h>
 
Int main (INT argc, char * argv [])
{
Int flag = 0;
Char passwd [10];
 
Memset (passwd, 0, sizeof (passwd ));
 
Strcpy (passwd, argv [1]);
 
If (0 = strcmp ("linuxgeek", passwd ))
{
Flag = 1;
}
 
If (FLAG)
{
Printf ("\ n password cracked \ n ");
}
Else
{
Printf ("\ n incorrect passwd \ n ");
 
}
Return 0;
}
A: The key to cracking the preceding encryption is to use the strcpy () function. Therefore, when users Input random passwords to the passwd cache, they do not check whether the capacity of passwd is sufficient in advance. Therefore, if you enter a long "password" that is sufficient to cause cache overflow and overwrite the default value of the "flag" variable, even if the password cannot pass verification, the flag verification bit becomes non-zero, so that the protected data can be obtained. For example:

$./Psswd aaaaaaaaaaaaa
 
Password cracked
Although the above password is incorrect, we can still bypass password security protection through cache overflow.

To avoid this problem, we recommend using the strncpy () function.

Note: The latest compiler detects the possibility of stack overflow internally, so it is difficult to store variables in the stack to cause stack overflow. This is the case by default in my GCC, so I have to use the compile command '-fno-Stack-Protector' to implement the above scheme.

3. Main () return type

Q: Can the following code be compiled? If yes, is there any potential problems?

# Include <stdio. h>
 
Void main (void)
{
Char * PTR = (char *) malloc (10 );
 
If (null = PTR)
{
Printf ("\ n malloc failed \ n ");
Return;
}
Else
{
// Do some processing
Free (PTR );
}
 
Return;
}
A: Because of the return type of the main () method, errors in this Code are considered as warnings in most compilers. The return type of main () should be "int" rather than "Void ". Because the "int" return type causes the program to return the status value. This is very important, especially when a program is running as part of a script dependent on the successful running of the program.

4. Memory leakage

Q: Will the following code cause memory leakage?

# Include <stdio. h>
 
Void main (void)
{
Char * PTR = (char *) malloc (10 );
 
If (null = PTR)
{
Printf ("\ n malloc failed \ n ");
Return;
}
Else
{
// Do some processing
}
 
Return;
}
A: Although the above Code does not release the memory allocated to the "PTR", it does not cause memory leakage after the program exits. After the program ends, all the memory allocated by the program will be automatically processed. However, if the above Code is in a "while loop", it will lead to a serious memory leakage problem!

Tip: If you want to know more about memory leakage and memory leak detection tools, you can refer to our article on valgrind.

5. Free () function

Q: The following program will cause a problem when the user inputs 'freeze ', but 'zebra' won't. Why?

# Include <stdio. h>
 
Int main (INT argc, char * argv [])
{
Char * PTR = (char *) malloc (10 );
 
If (null = PTR)
{
Printf ("\ n malloc failed \ n ");
Return-1;
}
Else if (argc = 1)
{
Printf ("\ n usage \ n ");
}
Else
{
Memset (PTR, 0, 10 );
 
Strncpy (PTR, argv [1], 9 );
 
While (* PTR! = 'Z ')
{
If (* PTR = '')
Break;
Else
PTR ++;
}
 
If (* PTR = 'Z ')
{
Printf ("\ n string contains 'Z' \ n ");
// Do some more processing
}
 
Free (PTR );
}
 
Return 0;
}
A: The problem here is that the Code (by adding "PTR") modifies the address stored by "PTR" in the while loop. When "ZEBRA" is input, the while loop is terminated before execution. Therefore, the variable passed to free () is the address passed to malloc. But in freeze, the address stored by PTR will be modified in the while loop, resulting in an error in the address passed to free (), resulting in seg-fault or crash.

6. Exit with _ exit

Q: In the following code, atexit () is not called. Why?

# Include <stdio. h>
 
Void func (void)
{
Printf ("\ n cleanup function called \ n ");
Return;
}
 
Int main (void)
{
Int I = 0;
 
Atexit (func );
 
For (; I <0 xffffff; I ++ );
 
_ Exit (0 );
}
This is because the use of the _ exit () function does not call functions such as atexit () to clean up. If you use atexit (), you should use exit () or "return" in combination with it.
7. Void * and C struct

Q: Can you design a function that can accept any type of parameters and return interger (integer) results?

A:

Int func (void * PTR)
If this function has more than one parameter, this function should be called by a struct, which can be filled by parameters to be passed.

8. * And ++ operations

Q: What will the following operations output? Why?

# Include <stdio. h>
 
Int main (void)
{
Char * PTR = "Linux ";
Printf ("\ n [% C] \ n", * PTR ++ );
Printf ("\ n [% C] \ n", * PTR );
 
Return 0;
}
A: The output result is as follows:

[L]
 
[I]
Because "++" and "*" have the same priority, "* PTR ++" is equivalent to "* (PTR ++ )". That is, you should first execute PTR ++ and then * PTR, so the operation result is "L ". The second result is "I ".

9. Q: modify the code snippet (or read-only code)

Q: The following code segment is incorrect. Can you point it out?

# Include <stdio. h>
 
Int main (void)
{
Char * PTR = "Linux ";
* PTR = 'T ';
 
Printf ("\ n [% s] \ n", PTR );
 
Return 0;
}
A: This is because * PTR = 'T' will change the first letter of the code segment (read-only code) "Linux" in the memory. This operation is invalid and may cause seg-fault or crash.

10. The process will change its name

Q: Can you write a program that changes the name of your process at runtime?

A: See the following code:

# Include <stdio. h>
 
Int main (INT argc, char * argv [])
{
Int I = 0;
Char buff [100];
 
Memset (buff, 0, sizeof (buff ));
 
Strncpy (buff, argv [0], sizeof (buff ));
Memset (argv [0], 0, strlen (buff ));
 
Strncpy (argv [0], "newname", 7 );
 
// Simulate a wait. Check the process
// Name at this point.
For (; I <0 xffffffff; I ++ );
 
Return 0;
}
11. Return the address of the local variable

Q: Is there a problem with the following code? If yes, how can I modify it?

# Include <stdio. h>
 
Int * Inc (INT Val)
{
Int A = val;
A ++;
Return &;
}
 
Int main (void)
{
Int A = 10;
Int * val = Inc ();
Printf ("\ n incremented value is equal to [% d] \ n", * val );
 
Return 0;
}
A: Although the above programs sometimes run normally, there are serious vulnerabilities in "Inc. This function returns the address of the local variable. Because the life cycle of the local variable is the life cycle of "Inc ()", it is difficult to use the local variable after Inc ends. This can be avoided by the address of the variable "A" in main (), so that the stored value of this address can be modified later.

12. Process printf () Parameters

Q: What will the following code output?

# Include <stdio. h>
 
Int main (void)
{
Int A = 10, B = 20, c = 30;
Printf ("\ n % d .. % d .. % d \ n ", A + B + C, (B = B * 2), (C = C * 2 ));
 
Return 0;
}
A: The output result is:

110 .. 40 .. 60
This is because the function parameters in C language are processed from right to left by default, and the output is from left to right.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.