[Issue 1393] New: Phobos needs strnlen()

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Jul 31 19:34:15 PDT 2007


http://d.puremagic.com/issues/show_bug.cgi?id=1393

           Summary: Phobos needs strnlen()
           Product: D
           Version: 1.015
          Platform: PC
        OS/Version: Linux
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: bugzilla at digitalmars.com
        ReportedBy: cdunn2001 at gmail.com


std.c.string needs strnlen().  Here is why:

struct Person{
  char name[32];
  char addr[128];
};

A bunch of these could be stored on disk.  After loading, we want to compare
'name' to another array.  But how?  We can use strncmp(), but we need to know
the length of 'name'.  It is NOT 32.  We cannot use strlen() safely on 'name'
because it might not be null-terminated.

We need to do this:
---
int compare(char[] lhs, char[] rhs){
  char* lptr = cast(char*)lhs;
  char* rptr = cast(char*)rhs;
  ulong len_lhs = strnlen(lptr, lhs.length);
  ulong len_rhs = strnlen(rptr, rhs.length);
  int comp = std.c.string.strncmp(lptr, rptr, min!(uint)(len_lhs, len_rhs));
  if (comp) return comp;
  if (len_lhs < len_rhs) return -1;
  else if (len_lhs > len_rhs) return 1;
  else return 0;
}

bool foo(Person* p){
  return !compare(p.name, "Christopher");
}
---
Of course, std.string.strlen(char[] s) could also be useful.  It should return
the length to the first null, or s.length.  And my compare() function could be
there too.  But those are not critical.  strnlen() is.  If it's not there,
people will use strlen() and cause buffer overflows.



More information about the Digitalmars-d-bugs mailing list