strndup有什么问题?

Zhu*_*gqi 3 c macos flex-lexer

我正在使用flex编写解析器.我使用的是Mac OS X 10.6.7.我已经包含这样的头文件:

#include "string.h"
#include "stdlib.h"
Run Code Online (Sandbox Code Playgroud)

但它说

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

为什么?

Ric*_*ard 5

AFAIK在string.h或stdlib.h中没有方法strndup,尝试使用strdup(),这可能是你想要的.如果你真的需要指定你想要分配的长度,你可以使用malloc和memcpy来实现.

  • 这不完全正确 - [`strndup`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strndup.html)是"标准",但该标准尚未广泛实施(尚未实施).它已经在GLIBC中作为延伸存在了很长一段时间.(但是+1无论如何,malloc + strcpy是一个很好的解决方法.) (3认同)
  • 注意,如果你想要类似'strndup`的行为,你应该使用`memchr`(在`n`字节中搜索空字节)来查找长度,添加1,`malloc`,然后`memcpy`,最后添加null终止符.从来没有必要使用`strncpy`. (2认同)