Write security code-don't compare Structure_structure with memcmp

Source: Internet
Author: User
This article's copyleft belongs to gfree.wind@gmail.com all, uses the GPL to publish, may copy freely, reprint. But reproduced please keep the integrity of the document, indicating the original author and the original link, is strictly prohibited for any commercial purposes.
Author: gfree.wind@gmail.com
Blog: linuxfocus.blog.chinaunix.net


Take a look at the code below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct PADDING_TYPE {
Short M1;
int m2;
} padding_type_t;


int main ()
{
padding_type_t A = {
. M1 = 0,
. m2 = 0,
};
padding_type_t b;


memset (&b, 0, sizeof (b));


if (0 = = memcmp (&a, &b, sizeof (a)) {
printf ("equal!\n");
}
else {
printf ("No equal!\n");
}


return 0;


}
Let's think about what the result is.
laptop:~/works/test$ gcc-g test.c
laptop:~/works/test$./a.out
No equal!
Why is that so? In fact, experienced development will immediately respond, this is due to the alignment caused.
Yes, because the type of the struct PADDING_TYPE-&GT;M1 is short, and the M2 type is int, according to the principle of natural alignment. Each member of the Padding_type needs to be aligned to 4 bytes. The compiler then inserts 2 padding bytes after the M1, and the padding byte values are random. That is, the value of the padding byte in A is random, while the padding in B is zeroed. So when using Memcmpy to compare the two structures, the return value is unequal.


From this example, we should keep in mind that when comparing structures, do not use byte comparisons, such as memcmp. Unless you're the one to ensure that these aligned padding bytes are zeroed out. Otherwise, you will get unexpected results.

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.