Sophomore last semester, had written such a piece of code
#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!= ' ")
printf ("%c ", *ptr2++);
return 0;
}is to use the malloc function to apply for less than str1 space, and then copy str1 into this space, found that the final can print out the full Helllo world, is not the application of memory has strlen (PTR1)-2?
A friend said so.
"In fact, this situation is normal (it is undesirable to do so)." Find some information to look at the smallest block of memory, that is, memory has a minimum, no matter how small you apply, it will be so big. This is to speed up the addressing.
For example, the address you malloc out of is always an even number, not an odd number (assuming, of course, an even address approach).
Just a personal understanding, you can refer to byte alignment. "
I feel very reasonable, and then I did a test, only apply 6 characters of space, and then a very long string to pay str1, so that the size of this string must be more than the so-called memory of the smallest block, the result is very good, and indeed there was an anomaly ~
This is not only a matter of thinking, but of efficiency, forgetting the book, that is, double and float are the best choice double, which should be almost the same for efficiency, but double is much better than float.
Then we can also apply for the smallest piece of memory. Ask for advice from friends