Mac OS上basename的怪异行为

问题描述

我有一个简单的程序可以测试basename()方法

#include <stdio.h>
#include <string.h>
//#include <libgen.h>

int main (int argc,char **argv)
{
    char *a = strdup("test();");
    printf("%s",basename(a));
    return 0;
}

clang抱怨,但仍然可以编译。

test.c:7:18: warning: implicit declaration of function 'basename' is invalid in C99 [-Wimplicit-function-declaration]
    printf("%p",basename(a));
                 ^
test.c:7:18: warning: format specifies type 'void *' but the argument has type 'int' [-Wformat]
    printf("%p",basename(a));

这会导致段错误。但是,如果我添加了libgen.h标头,它将正常工作。

我已经用otool检查了二进制文件,它与同一个dylib链接,仅此而已。为什么第一个崩溃?

我已经检查过the answer here,它使用了静态缓冲区,但是我使用了strdup()的结果,所以这是一个不同的问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)