What's wrong with strndup?

若如初见. 提交于 2019-12-10 19:44:08

问题


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?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/6062822/whats-wrong-with-strndup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!