简体   繁体   English

strndup有什么问题?

[英]What's wrong with strndup?

I'm writing a parser using flex. 我正在使用flex编写解析器。 I'm using Mac OS X 10.6.7. 我使用的是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? 为什么?

AFAIK there is no method strndup in string.h or stdlib.h, try using strdup() which is probably what you want. AFAIK在string.h或stdlib.h中没有方法strndup,尝试使用strdup(),这可能是你想要的。 If you really need to specifiy the length you want allocated you could do it using malloc and memcpy instead. 如果你真的需要指定你想要分配的长度,你可以使用malloc和memcpy来实现。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM