The traps and defects in C Language

Source: Internet
Author: User

The following describesC LanguageTraps and defects:

Lexical traps:

1. = different from = do not write errors in the program. Be careful. When comparing expressions with constants, you can place Constants on the left.

2. & | different from & |.

3. Greedy method in lexical analysis: each symbol should contain as many characters as possible. If the compiler's) input stream has been decomposed into symbols before a character, the next symbol will include the longest string that may constitute a character from the character. For example, if y = x/* p,/* is treated as a symbol.

4. If the first character of an integer is 0, the constant is regarded as an octal number.

5. Char c = 'cxf '. In vc and Gcc, the last character is used to overwrite the previous character, and the final integer is the integer of the last character.

Syntax trap:

1. The c variable declaration is composed of a type and a set of similar expressions. The declaration Operator is similar to the expression, and returns a result of the given type in the Declaration. Such as float f, f )).

Once you know How to declare a variable, the type conversion operator of this type is easy to get: remove the variable name and semicolon in the Declaration, then, encapsulate the remaining parts with parentheses. Float * h), float *) is the type conversion character "pointing to a pointer to a function of the floating point type returned value. * Void *) Call the routine with the address 0.

2. Operator priority: single object operator, arithmetic operator, shift, relation, logic, condition, and value assignment.

3. Do not forget the break in the case in the switch statement. If you want to omit it, add a comment.

4. The C language only contains one-dimensional arrays, And the array size must be determined as a constant during compilation. Multi-dimensional arrays are simulated through one-dimensional arrays, because the elements of an array can be any object or an array.

For an array, we can only do two things to determine its size and obtain a pointer to the element whose subscript is 0. Other operations related to arrays are actually performed through pointers.

Semantic traps:

1. a null pointer is not equal to a null string. The compiler ensures that the pointer converted from 0 is not equal to any valid pointer. When 0 is assigned to a non-pointer variable, you must not attempt to use the content stored in the memory to which the Pointer Points.

2. Use asymmetric boundary mode when using the range. The first is the first occupied element in the "entry point" sequence), and the second is the first released element in the "entry point" sequence ). Forint I = 0; I <10; I ++ ). Do not use Forint I = 0; I <= 9; I ++ ).

3. If the subscript of an array is expressed as 10 elements by adding an exit interface to the inbound interface, its subscript is 0 <= n <10 ), the number of elements is the difference between the upper and lower bounds, that is, the lower bounds. If it is null, the upper bound is equal to the lower bound. In any case, the upper bound cannot be smaller than the lower bound.

Use the asymmetric boundary method whenever possible.

An array with N elements, we can use a [N] for comparison and assignment, but cannot reference its content.

4. There are only four operators in the C language in the specified order of evaluation: &, | ,? : And ,. The order in which other operators evaluate the operator operands is undefined. In particular, the value assignment operator does not guarantee any order of value. Y [I] = X [I ++] error.

5. Remember to provide the return value for main.

Connection:

1. To avoid naming conflicts, use the static modifier for variables or functions. To define a function with the same name as a library function, you can add static modification to the function to be defined in the file.

2. Before using external functions, you must declare them. Otherwise, if no declaration is made, the return value of the function is an integer by default.

3. The external Declaration must be consistent with the definition type. It cannot be declared as extern int n, but is defined as long n.

4. the same external variable is declared as different types in different places. Most compilers cannot detect this error.

 
 
  1. char file[]= "/etc/password"; 

And

 
 
  1. extern char* file; 

Is different.

Library functions:

1. Pay attention to getchar). The return value is an integer, not a struct type.

2. In order to maintain the downward compatibility with programs that cannot perform read/write operations at the same time in the past, an input operation cannot follow an output operation directly. If the input and output operations are performed simultaneously, you must insert a call to the fseek function. Example:

 
 
  1. FILE *fp;  
  2. struct record rec;  
  3. while (fread((char *)&rec, sizeof(rec),1,fp) = 1)  
  4. {  
  5. if(/* */)  
  6. {  
  7. fseek(fp, -(long)sizeof(rec), 1);  
  8. fwrite((char *)&rec, sizeof(rec), 1,fp);  
  9. fseek(fp, 0l,1);  
  10. }  

3. Buffer output and memory allocation:

You can use the setbuf function to control the buffer output of the program.

 
 
  1. #include <stdio.h>  
  2. void main(void)  
  3. {  
  4. int c;  
  5. char buf[BUFSIZ];  
  6. setbuf(stdout,buf);  
  7.  
  8. while((c = getchar()) != EOF)  
  9. putchar(c);  

This is wrong. When was the last buf cleared? The answer is that after the main function is completed, it is part of the cleanup required by the C Runtime Library before the program is handed back to the operating system. However, before that, the buf has been released.

The solution is to add the static declaration. You can also move the buf declaration out of the main function. The second method is to dynamically allocate the buffer, and the allocated buffer is not automatically released in the program.

4. You cannot directly use errno to detect errors. First, check the returned value as an error indicator to confirm that the program has failed. Then, check errno to find out the cause.

/* Call the library function */

If returned error value)

Check errno

5. database function signal

Theoretically, a signal may occur at any time during the execution of the C program, or even during the execution of some complex library functions such as malloc.

Therefore, from a security perspective, the signal processing function should not call the above-mentioned database functions. For the same reason, exit using longjump in the signal processing function, which is usually not safe because the signal may occur in malloc or other library functions to update a data structure, but there is no final completion process. Therefore, it seems that the signal processing function can only set a flag and return it. It is expected that the main program will check the flag and find that a signal has occurred.

However, this is not always safe. When an arithmetic operation error raises a signal, some machines will re-execute the failed operation after the signal processing function returns. Therefore, for arithmetic operation errors, the only secure and portable operation of the signal processing function is to print an error message and immediately exit the program using longjump or exit.

When a program ends abnormally, the last few lines output by the program are often lost because of buffering.

Pre-processor:

1. Do not ignore the brackets in the macro.

2. macros are not functions. Enclose the parameters in the macro with parentheses to enclose the entire result expression. Prevent side effects.

3. macros are not statements: # define asserte) void) e) | _ assert_error_FILE _, _ LINE _)))

4. A macro is not a type definition. Do not use # define to define a type. Instead, use typedef to define a new type.

Portability:

1. Because a String constant can be used to represent a character array, it can be replaced with the end of a String constant when an array name appears. For example, "0123456789" [n % 10]

2. Pay attention to the changes in the C standard and the use of new features.

3. What the c standard can ensure is that the c implementation must be able to distinguish the first six characters from different external names, and it is not case sensitive. Avoid: print_char), print_int), etc.

4. Specify the relative length of an integer. Values of the short type must be in the int type, values of the int type must be in the long type, and values of a common int type must be in the long type) the integer is large enough to hold any array subscript. The character length is determined by the hardware features.

5. Maximum random number value: RAND_MAX

I hope that the introduction of the above content will help you to recognize the truth of some small knowledge.

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.