The problem of C-language dynamic application memory caused by strcpy function __ function

Source: Internet
Author: User

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

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.