What's wrong with strndup?
Asked Answered
B

3

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?

Byrnes answered 19/5, 2011 at 17:55 Comment(1)
Note that Mac OS X 10.10.2 (Yosemite) provides strndup() — and also strnlen().Tain
W
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.

Wiggs answered 19/5, 2011 at 17:58 Comment(3)
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.)Algae
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.Angelitaangell
strndup() is coming to C2x: see open-std.org/jtc1/sc22/wg14/www/docs/n2478.pdfVertievertiginous
C
5

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;
}
Ca answered 7/1, 2017 at 16:15 Comment(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.Pacifa
S
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.

Stamen answered 19/5, 2011 at 18:7 Comment(1)
@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.Lymphadenitis

© 2022 - 2024 — McMap. All rights reserved.