1

I have a simple program to test basename() method:

#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 complains but it compiles anyway.

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));

And it results in segfault. But if I added libgen.h header, it works normally.

I've checked the binary with otool, it linked against the same dylib, nothing else. Why does the first one crash?

I've checked the answer here already, it uses a static buffer but I use the result from strdup(), so it's a different question.

daisy
  • 22,498
  • 29
  • 129
  • 265

0 Answers0