0
点赞
收藏
分享

微信扫一扫

memmem未声明导致返回值不对的问题分析

辰鑫chenxin 2022-04-21 阅读 50
c++

搬运 memmem未声明导致返回值不对的问题分析 - ILD

在64位系统上,使用memmem接口,根据手册,memmem声明在string.h

代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

#include <stdio.h>

#include <termios.h>

#include <unistd.h>

#define _GNU_SOURCE

#include <string.h>

main()

{

    // 省略一些代码

    unsigned char *s = memmem(buf, 11, start, 3);

    printf("s %p buf %p\n", s, buf);

}

编译有告警:

serial.c:72:23: warning: implicit declaration of function ‘memmem’; did you mean ‘memset’? [-Wimplicit-function-declaration]                                                                               
    unsigned char *s = memmem(buf, 11, start, 3);
                       ^~~~~~
                       memset

serial.c:72:23: warning: initialization of ‘unsigned char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]

多次运行,打印结果如下:

s 0x219c794f buf 0x7fff219c794d

s 0xfffffffff3d81bfd buf 0x7ffdf3d81bfd

结果很奇怪,s应该是buf的子串,或者是NULL。为什么这么奇怪的值呢,访问s的时候还导致段错误。

后来分析,原来是memmem没声明,导致编译器认为返回值是int,而64位系统上,指针也是64位的,尽管memmem返回的值是64位的,但是编译器认为其是int,是32位的。因此不能将memmem的返回值完整的赋值给s。

至于没声明的原因是:_GNU_SOURCE这个定义应该放在所有c头文件的前面,或者在编译选项中-D_GNU_SOURCE。修改成如下就可以了:

1

2

3

4

5

6

#define _GNU_SOURCE

#include <stdio.h>

#include <termios.h>

#include <unistd.h>

#include <string.h>

举报

相关推荐

0 条评论