Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is strnlen function supported in C++, on codeblocks ide?

Tags:

c++

c++11

My program is:

#include <cstdio>
#include <cstring>
using namespace std;

int main(int argc,char **argv)
{
    const static size_t maxbuf=128;
    const char * s1="String one";
    char sd1[maxbuf];
    printf("length is %ld",strnlen(sd1,maxbuf));
    return 0;
}

Error is:

 strnlen was not declared in this scope

Questions:

  1. Why I am not able to use strnlen function in C++ on my codeblocks IDE?

  2. Is their a good alternative to strnlen?

like image 470
Devashish Lohani Avatar asked Nov 20 '25 09:11

Devashish Lohani


1 Answers

strnlen is a GNU extension and also specified in POSIX (IEEE Std 1003.1-2008). If strnlen is not available, which can happen when such extension is not supported, use the following replacement.

// Use this if strnlen is missing.
size_t strnlen(const char *str, size_t max)
{
    const char *end = memchr (str, 0, max);
    return end ? (size_t)(end - str) : max;
}

I gave an answer on a similar question here.

like image 118
HelloWorld Avatar answered Nov 21 '25 23:11

HelloWorld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!