macos strndup 有什么问题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6062822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's wrong with strndup?
提问by Zhu Shengqi
I'm writing a parser using flex. I'm using Mac OS X 10.6.7. I have already include header files like this:
我正在使用 flex 编写解析器。我使用的是 Mac OS X 10.6.7。我已经包含了这样的头文件:
#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?
为什么?
回答by Rickard
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.
AFAIK string.h 或 stdlib.h 中没有方法 strndup,请尝试使用 strdup() 这可能是您想要的。如果你真的需要指定你想要分配的长度,你可以使用 malloc 和 memcpy 来代替。
回答by Rickard
回答by Kjetil Hvalstrand
If you need a strndup implementation, you can use this one.
如果你需要一个 strndup 实现,你可以使用这个。
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;
}