Dynamic Memory application in C Language caused by strcpy Function

Source: Internet
Author: User

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

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.