Reputation: 1869
I want to compare 2 unsigned bytes in hex. This is what I tried:
if (memcmp (msgType , 0x00003336, 2 ) == 0){}
This is what gcc prints for msgType :
(gdb) x msgType
0x7fffffffbb84: 0x00003336
I'm getting segfault. How can I fix it?
I tried :
const unsigned char broadcast[2] = {0x33, 0x36};
But gdb shows:
(gdb) x broadcast
0x401e28 <broadcast>: 0x62723633
I need: 0x00003336
Upvotes: 1
Views: 4104
Reputation: 399713
The first two arguments to memcmp()
are pointers to the memory blocks to compare. See the manual page, the prototype is:
int memcmp(const void *s1, const void *s2, size_t n);
You are using the absolute address 0x00003336 as the value of s2
, which seems very wrong; that's not a valid address in the general case.
To fix this, you must create a memory area that holds the value you want to compare against, and pass a pointer to that as the second argument. Try:
const uint8_t data[] = { 0x36, 0x33 };
if(memcmp(msgType, data, sizeof data) == 0)
{
}
Note that the bytes are swapped in the above, on the assumption that you're on a little-endian system.
Upvotes: 3
Reputation: 39797
Both of memcmp()
's first two arguments must be pointers to memory. You seem to be passing in a value you want to compare against, rather than a pointer to that value.
Instead, try this:
unsigned short expectedValue = 0x3336;
if (memcmp (msgType, &expectedValue, 2) == 0){}
Upvotes: 0
Reputation: 234635
If your process does not own the memory at 0x00003336
then you will get undefined behaviour: manifested, in this particular instance, as a segfault.
The normal thing to do here is to pass a pointer to a variable that you have instantiated yourself.
Upvotes: 0
Reputation: 43662
You need a pointer as second argument, you can't just pass an hex value in there
http://www.cplusplus.com/reference/cstring/memcmp/
Something that might work:
#include <stdio.h>
int main(void) {
unsigned char msgType[2] = {0x33, 0x36};
unsigned char your_value[2] = {0x33, 0x36};
// Make sure your_value is the same size of msgType
if (memcmp (msgType , your_value, sizeof(msgType)/sizeof(unsigned char) ) == 0){
printf("Yes, memory is equal at that address!");
}
return 0;
}
Upvotes: 1