One of SolmyR's small piece series: Where is the string?

zhaozj2021-02-17  166

Painting outside: Today is a big sunny day, warm sunshine through the window into this spacious office, the people in the office are working hard in front of their respective computers, everything is so quiet, peaceful, normal ...

"Ah ~! Help! Solmyr You use the folder to me!"

"The stupidity should be punished."

Outer sound: ... Hey, ok, I have to recognize a little exception. This is a software company, which is called Zero, a new college student; here is elegant, it seems to be very cultivated, it is not like this, Solmyr, Senior Programmer, Responsible for the training of Zero's newcomers. Ah, the story begins ...

"What did I do?" Zero asked with his nose. "This time you take my folder and big one!"

"You come over to see the mistakes you committed." SolmyR turned out of Zero's first code:

... char * msg = "connectting ... please wait" ... if (status == s_connected)                                        "This is a very ordinary String declaration ", Zero is dissatisfied.

"You can't see it? Connect This word is in the past, you are missing, playing a T", SolmyR answers.

"Just for this, you use the folder to ignore me ... ah! This is a CD box!"

"This is a commercial software. You think it is chatting on QQ and PPMM. Don't be tight. What is wrong, I deliberately leave such a long time to give you, now you haven't found your true mistake? You are really not a general dish ~ "SolmyR deliberately dragging a long sound, satisfied with the edge of Zero out," Ok, let us start from the foundation, how is the string in the C language? "

"This I know", ZERO seems to be confident, "In the C / C language, the string is a continuous character memory cell, and each unit stores a character and uses \0 as the end of the end."

"So before we use the pointer ..."

"We should guarantee this pointer to legal memory, or point to a already existing memory, either dynamically assign a piece." Zero starts to show a proud smile - this level of problem, ha!

"Well! So where is the MSG in your code pointing?"

The smile is solidified.

"This ... oh ... I want ... It should point to a legal memory, because I have been working like this, it works ...", the Zero period Aii said.

"Legal memory? Who is all of this memory? How big is it? How long is the survival cycle? What special nature?"

"..."

"Hey!", Solmyr is sighing, "I know this. Ok, let us first start." SolmyR is fast to type as follows:

Char msg [] = "hello"; char * pmsg = (char *) Malloc (Sizeof ("Hello")); STRCPY (PMSG, "Hello"); "The above code you should be very clear: MSG is a The character array, the C language guarantee will assign a continuous memory for it, and initialize it to "Hello". PMSG is a character pointer, we call the malloc function to dynamically assign a memory, and fill its value with the strcpy function "Hello". The common point of these two practices is: First get a memory with normal means, then fill the value. Then look at this: "char * msg =" hello ";

"What does this mean? First, MSG is a pointer, and the C / C language is not responsible for assigning a memory for it; secondary, we have not explicitly assigned a memory. It points to" Hello ", you write directly The one in the code. "

"What is the one of the one '?" Directly written directly in the code, Zero reveals the confused expression

"You will understand:", SolmyR Type:

Double DB = 1.5;

"This line, 1.5 is something? It is a Double type constant, C / C language to handle them, but also to allocate memory to store these things. Similarly, when you write" Hello "in the code, actually The C / C language is assigned a memory to save this string. When you write char * msg = "hello", you just give the address of such a memory to the pointer MSG. So MSG does point to a legal memory, this It is sometimes the reason why this code can work. But do this, there is a lot of problems, I will ask you, what type is it to point to this memory? "

"Of course, char *", Zero does not answer.

"Wrong! It should be const char *. I want to be eared, the string written in the program You don't want it to change, so it is obvious that this memory should be interpreted as a constant. But what did you do when you declare MSG? ? "

"Hey ... I used a very square pointer to point to a constant string." This time, ZERO is obviously prudent. "

"Correct. Look at your original code, you not only point to it with a very quantity pointer, but also perform Strcpy on this pointer, write content in our compiler. What will happen?"

"Oh ... causing a runtime error?"

"Partially correct. Accurately, only when the engineering compilation option is debug version, if the engineering compilation option is a release version, everything is normal - strange? Do not, remember this: C / C allows you to break Any protection. So if the two lines of code have not been discovered in the debugging "," said that this, SolmyR stunned ZERO, "will be difficult to find."

"But what is it going to do so or not? MSG points to a legal memory, the content is correct, and it is not really written, what is it worried?", Zero complained.

SolmyR stepping into the cup, zero reflectivity immediately turning his face. "Don't worry, I just drink water." Solmyr faceless - If I ignore the hilarious words of his mouth - say, "Is there any harm? Take a look at the following code:" char * str1 = "Hello"; char * str2 = "hello"; * str1 = 'p'; cout << str2 << endl;

"Guess what is the result of running?", SolmyR adjusts the project settings while asked.

"Is this asked? Of course, it is an output hello."

"Answer the error, the correct answer is ...", Solmyr presses the run button, the screen display is actually Pello! .

ZERO is very surprised, scratching the head attempts to identify the logic, suddenly a light flash: "I understand! STR1 and STR2 actually point to the same memory! Because the C / C language is handling it when processing the Hello string When it is the same as, it has been optimized, only a Hello! Is this! "Zero excited to Solmyr.

"Well, it seems that you are not so sweet," SolmyR thumbs up, "But you still say something wrong: This is not a C / C language practice, is the practice of this compiler. Simple, you If you want to write this stroke, what is the result, it is not defined. The so-called no definition is that the C / C language is not guaranteed to get the result, which may also be like this, completely determined your compiler How do you think. Think about it, which day, your program has a weird problem - such as displaying information, chaos - what you wrote a string in the place where you have nothing to do? This is the biggest maintenance One of the nightmares. Now you understand where hazards? "

Zero has a big dream to wake up, nodded: "I know, I know."

"Know it, don't change it!"

......

Zero ran back to the seat to modify his procedure, the office was restored again, and all people were buried in their work. Only SolmyR sides while drinking coffee, lying on the temple, muttering ominous words: "This day is just beginning ..."

转载请注明原文地址:https://www.9cbs.com/read-31557.html

New Post(0)