5

I'm writing a parser using flex. I'm using Mac OS X 10.6.7. I have already include header files like this:

#include "string.h"
#include "stdlib.h"

but it says

Undefined symbols for architecture x86_64:
  "_strndup", referenced from:
      _yylex in ccl2332A.o
ld: symbol(s) not found for architecture x86_64

why?

1
  • 1
    Note that Mac OS X 10.10.2 (Yosemite) provides strndup() — and also strnlen(). Mar 13, 2015 at 1:47

3 Answers 3

6

AFAIK there is no method strndup in string.h or stdlib.h, try using strdup() which is probably what you want. If you really need to specifiy the length you want allocated you could do it using malloc and memcpy instead.

3
  • 4
    that's not completely correct - strndup is "standard", but that standard is not implemented widely (yet). It's been present in GLIBC as an extension for quite a while. (But +1 anyway, malloc + strcpy is a good workaround.)
    – Mat
    May 19, 2011 at 18:05
  • 2
    Note that if you want strndup-like behavior, you should use memchr (searching for a null byte in n bytes) to find the length, add 1, malloc that, and then memcpy and finally add the null terminator. There's never a need to use strncpy. May 19, 2011 at 18:34
  • 1
    strndup() is coming to C2x: see open-std.org/jtc1/sc22/wg14/www/docs/n2478.pdf
    – pmg
    Aug 27, 2020 at 18:24
4

strndup is a GNU extension and is not present on Mac OS X. You will have to either not use it or supply some implementation, like this one.

1
  • 6
    @R.. OS X 10.6 was certified as fully compliant POSIX 2003. It was released only three months after FreeBSD added an implementation of stndup. I think it's forgivable to not have pulled in a whole new kernel revision right before going gold. I believe 10.7 had this function.
    – matthias
    Jul 17, 2013 at 17:53
4

If you need a strndup implementation, you can use this one.

char *strndup(char *str, int chars)
{
    char *buffer;
    int n;

    buffer = (char *) malloc(chars +1);
    if (buffer)
    {
        for (n = 0; ((n < chars) && (str[n] != 0)) ; n++) buffer[n] = str[n];
        buffer[n] = 0;
    }

    return buffer;
}
1
  • 1
    Code-only answers are frowned Upon on stack Overflow, so you might want to add that "here is an implementation of strndup for those platforms that do not have it". BTW the size (chars) argument to strndup is of type size_t, which is distinct from int. Jan 7, 2017 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.