The test questions of C + + frequently test face

Source: Internet
Author: User
Tags assert
1. Analyze what's wrong with the following code.
void Test1 ()
{
 char string[10];
 char* str1 = "0123456789";
 strcpy (string, str1);

String str1 requires 11 bytes to hold (including the end of the ' "), and string only 10 bytes of space, strcpy will cause the array out of bounds; 2. Analyze the following code for problems.

void Test2 ()
{
    char string[10], str1[10];
    int i;
    For (i=0 i<10; i++)
     {
        str1  = ' a ';
     }
    strcpy (string, str1);
First, the code cannot be compiled at all. Because the array name str1 to the right value type of the Char *const type, the value cannot be assigned at all. Moreover, even if you want to assign a value to the first element of the array, use *STR1 = ' a '; Second, after assigning a value to a character array, a copy operation is performed using the library function strcpy, and the strcpy is copied back from the source address until the ' yes ' is encountered. So the length of the copy is variable. If you have not encountered the ' "', which leads to cross-border access to illegal memory, the program will collapse.
The perfect plan for modification is:
void Test2 ()
{
    char string[10], str1[10];
    int i;
    For (i=0 i<9; i++)
    {
        str1[i]  = ' a ';
    }
    STR1[9] = ' the ';
    strcpy (string, str1);
3. Indicate what is wrong with the following code.
void Test3 (char* str1)
{
 if (str1 = = NULL) {return
        ;
 }
 Char string[10];
 if (strlen (str1) <=)
 {
 strcpy (string, str1);
 }
}

if (strlen (str1) <= 10) should be changed to if (Strlen (STR1) < 10) Because the result of the strlen does not count the 1 bytes occupied by ' the '. 4. Write out the full version of the strcpy function

If you write a standard strcpy function with a total score of 10, here are the answers to several different points:
2 points

void strcpy (char *strdest, char *strsrc)
{while
  (*strdest++ = * strsrc++)!= ' ";
}

4 points

void strcpy (char *strdest, const char *STRSRC) 
//Adds a const to the source string, indicating that it is an input parameter, plus 2 points
{while
  (*strdest++ = * STRSR C + +)!= ' ";
}

7 points

void strcpy (char *strdest, const char *strsrc) 
{
 //Add 0 assertion to source address and destination address, plus 3
 assert ((strdest!= NULL) & & (Strsrc!= NULL));
 while ((*strdest++ = * strsrc++)!= ' ");
}

10 points

In order to realize chain operation, return the destination address, add 3 points.   
char * strcpy (char *strdest, const char *STRSRC) 
{
 assert ((strdest!= null) && (STRSRC!= null));
 char *address = strdest; 
 while ((*strdest++ = * strsrc++)!= ' "); 
 return address;
5. Check the following code for any problems.
void GetMemory (char *p)
{
 p = (char *) malloc (MB);
void Test (void) 
{
 char *str = NULL;
 GetMemory (str); 
 strcpy (str, "Hello World");
 printf (str);
}

The parameters passed into the getmemory (char *p) function are string pointers, and modifying the parameters inside the function does not really change the value of the incoming parameter, the execution
char *str = NULL;
GetMemory (str);
After STR is still null; 6. What happens to the following code?

Char *getmemory (void)
{ 
 char p[] = "Hello World"; 
 return p; 
}
void Test (void)
{ 
 char *str = NULL; 
 str = GetMemory (); 
 printf (str); 
}

Char p[] = "Hello World";
return p;
P[] Array is a local automatic variable within a function, and memory has been freed after the function returns. This is a common mistake many programmers make, the root of which is the failure to understand the lifetime of a variable.
# # #7. What is wrong with the following code?

void GetMemory (char **p, int num)
{
 *p = (char *) malloc (num);
}
void Test (void)
{
 char *str = NULL;
 GetMemory (&STR);
 strcpy (str, "Hello"); 
 printf (str); 
}
The parameters passed into the getmemory are pointers to string pointers, but the application memory and assignment statements are executed in the GetMemory
p = (char) malloc (num);
After not judging whether the memory is successful or not, add:
    if (*p = = NULL)
    {
     ...//Request memory failure processing
    }
Heap Memory not freed printf (str) to printf ("%s", str), otherwise you can use a formatted string to attack 8. What is the problem with the following code?
void Test (void)
{
 char *str = (char *) malloc (MB);
 strcpy (str, "Hello");
 Free (str); 
 ..//omitted other statements
}

In the implementation
Char str = (char) malloc (100);
The judgment that the memory is not applied for success is not followed; In addition, no str is empty after free (str), resulting in the possibility of becoming a "wild" pointer, plus:
str = NULL;
The malloc memory is also not released in the test function of question 6. 9. What's wrong with the following procedure?

Swap (int* p1,int* p2)
{
 int *p;
 *p = *P1;
 *P1 = *P2;
 *P2 = *p;
}
Requires a return value void in the Swap function, p is a "wild" pointer, which may point to the system area, causing the program to run a crash. In VC + + Debug runtime prompts for error "Access violation". The procedure should read:
void swap (int* p1,int* p2)
{
 int p;
 p = *p1;
 *P1 = *P2;
 *P2 = P;
}
10. Give the bool,int,float, the pointer variable and "0 value" comparison of the IF statement (assuming the variable name is Var)

Troubleshooting
BOOL type variable: if (!var)
int type variable: if (var==0)
Float type variable:
const float Epsinon = 0.00001;
if ((x >=-Epsinon) && (x <= Epsinon)
Pointer variable: if (var==null)
Analysis
Examination of the "internal strength" of the 0 value judgment, the 0 judgment of the bool variable can be written as if (var==0), and the int variable can also be written as if (!var), the judgment of the pointer variable can also be written as if (!var), although the procedure can run correctly, But the meaning of the procedure was not clearly expressed.
In general, if you want to let if judge a variable's "true", "false", you should use if (Var), if (!var) directly to indicate that it is "logical" judgment, if you use if to judge a numeric variable (short, int, long, etc.), should use if (var==0), It is a good programming habit to show that 0 is a "numerical" comparison, and that it is appropriate to use if (var==null) for the judgment pointer.
Floating-point variables are not accurate, so float variables cannot be used with "= =" or ". = "In contrast to numbers, it should be managed to be converted into" >= "or" <= "forms. If written as if (x = = 0.0), the sentence is wrong, 0 points. 11. The following is a 32-bit C + + program under Windows NT, please calculate the value of sizeof

void Func (char str[100])
{
 sizeof (str) =?
}
void *p = malloc (m);
sizeof (p) =?

sizeof (str) = 4
sizeof (P) = 4
Analysis
Func (char str[100]) function, the array name is used as a function parameter, in the function body, the array name loses its connotation, is only a pointer, loses its intension at the same time, it also loses its constant characteristic, may make the increment, the self reduction and so on the operation, may be modified.
The nature of the array name is as follows:
(1) The array name refers to a data structure, which is an array;
For example:
1
2
Char str[10];
cout << sizeof (str) << Endl;
The output result is 10,STR reference data structure CHAR[10].
(2) The array name can be converted to a pointer to its reference entity, and it is a pointer constant, which cannot be modified because it cannot be used for self increment and decrement.
Char str[10];
str++; Compilation error indicating that STR is not the left value
(3) When an array name is used as a function parameter, it is reduced to a normal pointer.
Under Windows NT 32-bit platform, the length of the pointer (memory size) is 4 bytes, so sizeof (str), sizeof (p) are 4. 12. Write a "standard" macro min, this macro enters two parameters and returns the smaller one. Also, what happens when you write the following code.

least = MIN (*p++, b);

Answer:
#define MIN (A,b) ((A) <= (B)? (A): (B))
MIN (*p++, b) can create side effects of macros
Analysis:
This question mainly examines the interviewer's use of the macro definition, a macro definition can implement a function-like work >> energy, but it is not a function at all, and the "arguments" in parentheses in a macro definition are not real arguments, and a one-to-one substitution is made for "parameters" when the > macro is expanded.
Programmers should be very careful about using macro definitions, with particular attention to two issues:
(1) Carefully enclose the "parameters" and the entire macro in the macro definition in parentheses. So, strictly > speaking, the following answers:
#define MIN (A,b) (A) <= (B)? (A): (B)
#define MIN (a,b) (A <= B?) A:B)
Should be sentenced to 0 points;
(2) To prevent the macro side effects.
Macro definition #define MIN (a,b) ((A) <= (B)? (A): (b) The result of the effect on min (*p++, b) is:
((*p++) <= (b)? (*p++): (b))
This expression will have side effects, and the pointer p will do 2 + + self-increment operations.
In addition, another answer that should be 0 points is:

This solution adds ";" to the macro definition, showing that the creator's concept of the macro is ambiguous and can only be ruthlessly sentenced to 0 points and eliminated by the interviewer. 13. Why standard header files have structures similar to the following.

#ifndef __incvxworksh
#define __INCVXWORKSH 
#ifdef __cplusplus
extern "C" {
#endif 
/*...*/ 
#ifdef __cplusplus
}
#endif 
#endif/* __incvxworksh * *

Compiled macros in header files

#ifndef __incvxworksh
#define __incvxworksh

The role is to prevent repeated references.
As an object-oriented language, C + + supports function overloading, while programming language C does not support it. A function is compiled by C + + in the symbol library with a different name than the C language. For example, suppose the prototype of a function is:
void foo (int x, int y);
The function is compiled by the C compiler in the symbol library with the name _foo, and the C + + compiler produces names like _foo_int_int. _foo_int_int such names contain function names and function parameters of the number and type of information, C + + is the test of this mechanism to achieve functional overload.
In order to implement the mixed programming of C and C + +, C + + has provided the specified symbol extern "C" to solve the name matching problem, the function declaration before the addition of extern "C", then the compiler will follow the C language to compile the function to _foo, so that the C language can call C + + of the function. Write a function that loops the string of a char to the right n. For example, the original is "Abcdefghi" if n=2, the shift should be "HIABCDEFG" function head is like this:
PSTR is a pointer to a string that ends with ' yes '
Steps is required to move n

void Loopmove (char * pstr, int steps)
{
 //Please fill ...
}

Correct solution 1:

void Loopmove (char *pstr, int steps)
{
 int n = strlen (pstr)-Steps;
 Char Tmp[max_len]; 
 strcpy (tmp, PSTR + N); 
 strcpy (tmp + steps, PSTR); 
 * (tmp + strlen (pstr)) = ' ";
 strcpy (PSTR, TMP);
}

Correct solution 2:

void Loopmove (char *pstr, int steps)
{
 int n = strlen (pstr)-Steps;
 Char Tmp[max_len]; 
 memcpy (tmp, PSTR + N, steps); 
 memcpy (pstr + steps, PSTR, n); 
 memcpy (PSTR, TMP, steps); 
}

Analysis
This test mainly examines the interviewer to the standard library function proficiency, when needs to reference the library function can greatly simplify the program writing the workload.
The most frequently used library functions include:
(1) strcpy
(2) memcpy
(3) Memset

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.