简体   繁体   English

使用memcmp时出现段错误

[英]Segfault while using memcmp

I want to compare 2 unsigned bytes in hex. 我想比较2个十六进制的无符号字节。 This is what I tried: 这是我尝试的:

if (memcmp (msgType ,  0x00003336, 2 ) == 0){}

This is what gcc prints for msgType : 这就是gcc为msgType打印的内容:

(gdb) x msgType
0x7fffffffbb84: 0x00003336

I'm getting segfault. 我遇到了段错误。 How can I fix it? 我该如何解决?

EDIT: 编辑:

I tried : 我试过了 :

const unsigned char broadcast[2] = {0x33, 0x36};

But gdb shows: 但是gdb显示:

(gdb) x broadcast
0x401e28 <broadcast>:   0x62723633

I need: 0x00003336 我需要: 0x00003336

The first two arguments to memcmp() are pointers to the memory blocks to compare. memcmp()的前两个参数是指向要比较的内存块的指针 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; 您使用绝对地址0x00003336作为s2的值,这似乎非常错误; 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. 请注意,假设您使用的是Little-endian系统,则在上面交换了字节。

You need a pointer as second argument, you can't just pass an hex value in there 您需要一个指针作为第二个参数,您不能只在其中传递一个十六进制值

http://www.cplusplus.com/reference/cstring/memcmp/ 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;
}

http://ideone.com/EQH6py http://ideone.com/EQH6py

If your process does not own the memory at 0x00003336 then you will get undefined behaviour : manifested, in this particular instance, as a segfault. 如果您的进程不拥有0x00003336处的内存,那么您将获得未定义的行为 :在这种特定情况下,表现为段错误。

The normal thing to do here is to pass a pointer to a variable that you have instantiated yourself. 此处的正常操作是将指针传递给您实例化的变量。

Both of memcmp() 's first two arguments must be pointers to memory. memcmp()的前两个参数都必须是指向内存的指针。 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){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM