Interesting things in C Language _ series of classical interview questions _ 3

Source: Internet
Author: User

I haven't learned the C language for some days. I watched windows the other day.ProgramDuring the design, find in VC 6 according to win's architecture

The following sectionCodeAnd found that their C language skills are really poor. The Code is the C code I see. So far, I can only understand it;

It is estimated that it will be easy to understand.

View code

Declare_handle (HDC );


# DefineDeclare_handle (name)
StructName ##__
{
IntUnused;
};
TypedefStructName ##__*Name

The above code will be shared with you after I understand it. Let's talk about this C language interview question.

8. Locate the wrong question
Find out the following function errors:
Question 1:
Void test1 ()
{
Char string [10];
Char * str1 = "0123456789 ";
Strcpy (string, str1 );
}

/*
At first glance, there is no error. The two real parameter types passed to the strcpy () function can meet the requirements.
However, we will find that this function has an out-of-bounds problem. The string "0123456789"
The length is strlen ("0123456789") + 1 = 11, and obviously string [10], it is impossible to store such a large space.
When using the strcpy function, you must consider the size of the source string and the target string.

*/
changing the function to the following form may be more robust:
int strcpy (const char * Source; char Dest [])
{< br> If (null = source | null = DEST | (strlen (DEST) return 1; // return value = 1 indicates that the replication failed
else
strcpy (DEST, source);
return 0; // return value = 0 indicates that the copy is successful
}< br>

Question 2:
void Test2 ()
{< br> char string [10], str1 [10];
int I;
for (I = 0; I <10; I ++)
{< br> str1 = 'a ';
}< br> strcpy (string, str1);
}< br>/*
two questions are examined:
1. The first address of an array is a constant and cannot be left. That is, str1 is a constant.
it represents the first address of the entire array.
2. subscripts must be used to reference the second array. In addition to assigning values like int iarray [10] = {1, 2} during initialization, you cannot assign values to array elements in batches elsewhere.
3. At the same time, the strcpy replication function is for character type variables with '\ 0', so the value assigned by this function
also excludes the value assignment.
*/
the following method is used to estimate the Robustness:
void Test2 ()
{< br> char string [10],
str1 [10];
for (INT I = 0; I <10; I ++)
str1 [I] = 'a ';
STR [9] = '\ 0';
strcpy (string, str1);
}

Question 3:
Void test3 (char * str1)
{
Char string [10];
If (strlen (str1) <= 10)
{
Strcpy (string, str1 );
}
}
// Question 3 also has the possibility of crossing the border. If strlen (str1) = 10, str1 actually occupies 11 spaces.
// The length returned by the strlen function is not counted as '\ 0. Pay attention to this.
The following method may be more robust:
Void test3 (char * str1)
{
Char string [10];
If (strlen (str1) <10 & null! = Str1)
Strcpy (string, str1 );
}

Question 4:
Void getmemory (char * P)
{
P = (char *) malloc (100 );
}

void test (void)
{< br> char * STR = NULL;
getmemory (STR);
strcpy (STR, "Hello World");
printf (STR );
}< br>/*
first, the problem of Memory leakage and pointer pointing to a blank address exists.
several problems exist in this question:
1. In the getmemory function, the return value of the malloc function is not tested.
If (null = P)
2. the pointer P is not released in the function.
free (p);
3. There is a problem, in C language, values are transmitted by default, not by address.
the STR direction cannot be changed in the program.
getmemory (STR); the point of STR cannot be changed.
the function is prototype:
void getmemory (char * P). It defines a pointer type parameter.
4. The value of the parameter cannot be changed inside the function
*/

/*****************
the essence of the malloc function is embodied in, it has a so-called idle linked list that connects available memory blocks into a long list. When calling the malloc function,
it searches for a memory block that is large enough to meet user requests along the connection table. The memory block is then split into two parts (the size of one part is equal to the size of the user request
, and the size of the other part is the remaining bytes ). Next, pass the memory allocated to the user, and return the remaining memory (if
exists) to the connection table. When the free function is called, it connects the memory block released by the user to the idle chain. At the end, the idle link will be cut into many small memory segments. If the user requests a large memory segment, there may be no fragments on the idle link that meet user requirements. Therefore,
the request latency of the malloc function, and began to rummaging through the idle chain to check and sort out the memory segments, merge adjacent small idle blocks into larger
memory blocks. If you cannot obtain a memory block that meets the requirements, the malloc function returns a null pointer. Therefore, when calling malloc to dynamically apply for a memory block, you must
determine the return value.
***************/

The following format may be more robust:
Void getmemory (char ** P)
{
Char * temp;
If (null! = (Temp = (char *) malloc (1000 )))
* P = temp;
Free (temp );
}

Question 5:
Char * getmemory (void)
{
Char P [] = "Hello World ";
Return P;
}

Void test (void)
{
Char * STR = NULL;
STR = getmemory ();
Printf (STR );
}

/* In fact, what should I do? This question is easier to understand than the previous one, but through this question and the above
You need to know the fact:
That is, the local variables declared in the function (except for static type and register type ).
It is an auto variable, and its memory space is applied in the stack opened by the system for applications.
The space applied for by the malloc function is applied from the heap opened by the system for the application. The application in the heap will not be automatically released,
The application in the stack will be automatically released as the function declaration cycle ends.
This question is wrong because it does not understand the lifecycle of local variables.
*/
The following format may be more robust:
Char * getmemory (void)
{
Char * P = NULL;
If (null! = (P = (char *) malloc (strlen ("Hello word") + 1 ))
Return P;
}

/*

However, the pointer returned in this way is free and meaningless.

*/
 

Question 6:

Void getmemory (char ** P, int num)
{
* P = (char *) malloc (Num );
}

Void test (void)
{
Char * STR = NULL;
Getmemory (& STR, 100 );
Strcpy (STR, "hello ");
Printf (STR );
}
/*
This topic has been implemented and discussed in the fourth topic.
It refers:
The value of & STR cannot be changed.
*/

Question 7:

Void test (void)
{
Char * STR = (char *) malloc (100 );
Strcpy (STR, "hello ");
Free (STR );
... // Other omitted statements
}
/*
This question is simpler than above. The problem is that the malloc function is not returned.
Detection,
If null = (char *) malloc (Num), The strcpy function will not be executed successfully,

*/

 

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.