Sophomore year, I wrote such a piece of code last semester.
# Include <stdio. h> # include <stdlib. h> # include <string. h> int main () {char * ptr1 = "Hello string"; char * ptr2 = (char *) malloc (strlen (ptr1)-2); strcpy (ptr2, ptr1); While (* ptr2! = '\ 0') printf ("% C", * ptr2 ++); Return 0 ;}
It is to use the malloc function to apply for less space than str1, and then copy str1 to this space. It is found that the helllo world can be completely printed, isn't the applied memory more than strlen (ptr1)-2?
A friend said this.
"In fact, this situation is normal (of course the practice is not advisable ).. for more information, see the minimum block of the memory. That is to say, there is a minimum block in the memory. No matter how small you apply, it will be so large. this is to accelerate addressing.
For example, if your malloc address is always an even number, it will not be an odd number (the premise is even address addressing ).
For more information, see byte alignment ."
I felt very reasonable. Later I tested and applied for a space of 6 characters, and then paid str1 a long string, so that the size of this string must exceed the so-called minimum memory block. The result is very good, and an exception occurs ~
This not only raises the question of efficiency, but forgets what I mentioned in this book. Double is the best choice between double and float. The efficiency of the two is almost the same, however, the precision of double is much better than that of float.
Can we also apply for the minimum memory? Ask your friends for advice