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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 08:04:15  来源:igfitidea点击:

What's wrong with strndup?

cmacosflex-lexer

提问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

strndupis 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.

strndup是一个 GNU 扩展,在 Mac OS X 上不存在。你要么不使用它,要么提供一些实现,比如这个

回答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;
}