2

I'm porting the program from C to C++ including this code:

char* get_file_extension(const char* file_name)
{
    char* e = strrchr((char*) file_name, '.');
    if (e == NULL)
    {
        char* buf = strdup(file_name);
        return buf;
    }
    return e + 1;
}

Assuming that I'm only changing compiler to c++11, is it enough to just change NULL to nullptr in this case? Currently strrchr is from included header string.h, so I'm afraid if strrchr return NULL instead of nullptr and if(e == nullptr) check fail.

Or should I change string.h to cstring?

frozenca
  • 839
  • 4
  • 14
  • Why the cast in the call to `strrchr` ? – Paul R Feb 21 '18 at 07:41
  • 1
    How is the memory for `file_name` being allocated because `strdup` uses `malloc`? – Galik Feb 21 '18 at 07:52
  • @PaulR - There are two `strrchr` overloads in the C++ version of the standard library. One for const pointers and one for non-const pointers. The cast may be to get the desired one. And the C version is a disgrace as far as const correctness goes. – StoryTeller - Unslander Monica Feb 21 '18 at 07:56
  • 3
    This function just looks very dangerous to me. It is a confusing mix of const/non-const, owned/non-owned pointers. I don't even understand what it does. If the string has a `'.'` it returns a substring pointer otherwise it duplicates the entire string?? – Galik Feb 21 '18 at 07:57
  • 1
    Fwiw, I suspect you want something more along the lines of: `const char* get_file_extension(const char* file_name) { if(auto e = std::strrchr(file_name, '.')) return e + 1; return ""; }` – Galik Feb 21 '18 at 08:10
  • 1
    Do you realise you can usually compile code as C, and then link it into your C++ project using your linker? – autistic Feb 21 '18 at 08:14

1 Answers1

5

strrchr returning NULL is an inaccurate statement. NULL is a macro that expands to a null pointer constant. A null pointer constant is implicitly convertible to a null pointer of any pointer type. What strrchr returns is a null pointer constant that is converted to a char* null pointer.

nullptr is also a null pointer constant, with some special properties. But most of them are immaterial to us. When you compare it to a null pointer, of any type, the comparison will yield true if the pointer is a null pointer.

As a matter of fact, even nullptr == NULL is perfectly fine and will give you the sane result.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458