A tip in the Platform Framework in Linux Kernel

Source: Internet
Author: User

First, the function prototype is given:

Struct platform_device * platform_device_alloc (const char * Name, int ID)
{
Struct platform_object * pA;

Pa = kzarloc (sizeof (struct platform_object) + strlen (name), gfp_kernel );
If (PA ){
Strcpy (Pa-> name, name );
Pa-> pdev. Name = pa-> name;
Pa-> pdev. ID = ID;
Device_initialize (& pa-> pdev. Dev );
Pa-> pdev. Dev. Release = platform_device_release;
}

Return pa? & Pa-> pdev: NULL;
}

The key lies in:

Pa = kzarloc (sizeof (struct platform_object) + strlen (name), gfp_kernel );

In my first day, I didn't add 1 to strlen, but it wasn't '/0' behind the structure. Isn't it out of memory?

View struct definitions:

Struct platform_object {
Struct platform_device pdev;
Char name [1];
};

My doubts have been solved!

The key lies in char name [1];
In this way, the struct will add a piece of memory (not necessarily a byte) in the structure alignment mode when allocating memory. If it is a regular 32-bit compiler, if it is aligned in four bytes, It is 4 bytes.

Even if you hit a comrade without the '/0' concept, the data will not cross the border. In the future, we must apply this technique in practice. This tactic can greatly increase the robustness of the project.

In addition, during the copy process:

Strcpy (Pa-> name, name );

The four bytes of the needle are saved and the space of the four bytes is saved.

I have learned a lot about Linux.

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.