Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get a doubt about the memcmp function. Let us assume we have a struct that require alignment:
struct exmp{
char a,
char b}

Probabily sizeof(exmp) is going to be 4. Two bites are actually used and two bites required to align.
Therefore when I call memcmp(exmpptr1, exmpptr2, sizeof(exmp)), this function is going to compare also the two bites required from alignment.
Is this going to bug the answer in a generic comparison, or the standard requires that the not used bites must be set to some value? So it is robust and portable code?

What I have tried:

It is not repeteable and is platform dipendent.
Posted
Updated 15-Sep-16 3:09am
Comments
Richard MacCutchan 15-Sep-16 5:13am    
memcmp is only any use for comparing arrays of bytes. Any other structure, class etc., will most likely give wrong results, at least some of the time, so cannot be relied on.

It's going to be a problem: unused bytes do not have to be set to any specific value (and it may differ between debug and release mode, not just from system to system as debug code often contains "check values" to make sure you don't exceed limits).

You have to be very, very careful when you start comparing anything by casting it to a "wrong" type: it can give you very odd results. For example, some systems store integers as least significant first, some as most significant first (Little or Big Endian) so comparing even a 16 bit integer with a 32 bit integer as unsigned char pointers could give you the wrong results.
 
Share this answer
 
Quote:
Is this going to bug the answer in a generic comparison, or the standard requires that the not used bites must be set to some value? So it is robust and portable code?
While it is not a memcmp bug, it can give unexpected results because the standard doesn't require (as far as I know) a specific value for the padding bytes.
 
Share this answer
 
If you want to compare C structures using memcmp you must just ensure that the structures does not contain padding bytes. How to do this depends on the used compiler.

With the Microsoft compiler use pack[^]:
C++
#pragma pack(push, 1)
struct exmp {
    char a;
    char b;
};
#pragma pack(pop)

With GCC use the packed attribute (see Common Type Attributes - Using the GNU Compiler Collection (GCC)[^]):
C++
struct __attribute__ ((__packed__)) exmp {
    char a;
    char b;
};
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900