gharel
gharel

Reputation: 573

Issue with returning a heap char pointer from a function

This code works:


        char* CFichierTrace::ConvertBSTRToString(BSTR* str)
        {
           if ( str == NULL )
           {
              char* buf = new char[2];
              sprintf_s(buf, 2, "%s", "");

              return buf;
           }
           else
              return _com_util::ConvertBSTRToString(*str);

        }

But I am trying to avoid multiple returns, bad programming I have been told. However it just wont work:



        char* CFichierTrace::ConvertBSTRToString(BSTR* str)
        {
           // char* result = new char[1];  (attempt #1, produces garbage as output)
           char* result = (char*) malloc(1 *sizeof(char)); (attempt #2, more garbage as output)

           if ( str == NULL )
           {
              char* buf = new char[2];
              sprintf_s(buf, 2, "%s", "");

              result = buf;
           }
           else
              result = _com_util::ConvertBSTRToString((BSTR) str);

          return result;

        }

There is an article about returning the string as a char** in argument (by ref), but I don't understand why a char* from the heap cannot be returned ?

Upvotes: 0

Views: 180

Answers (3)

Deduplicator
Deduplicator

Reputation: 45674

I just suppose you know why you pass a pointer to a BSTR, instead of a BSTR.

char* CFichierTrace::ConvertBSTRToString(BSTR* str) {
    return _com_util::ConvertBSTRToString(*str);
}

Due to BSTR-semantics, this is the proper implementation.
To clarify, all proper BSTR-functions treat NULL identical to a 0-length BSTR.

Anyway, use multiple return points wherever they make sense, unless you have a broken coding-standard disallowing such.

Upvotes: 2

Andrei Bozantan
Andrei Bozantan

Reputation: 3941

   char* CFichierTrace::ConvertBSTRToString(BSTR* str)
   {
       char* ret;
       if ( str == NULL )
       {
          ret = new char[1];
          ret[0] = 0;
       }
       else
          ret =  _com_util::ConvertBSTRToString(*str);

       return ret;
    }

And btw, you should not mix C++ new with C malloc. Also, it is arguable that multiple return points is a bad practice. There are many situations when the code is more readable when you have multiple return points.

Upvotes: 2

nos
nos

Reputation: 229224

You'd do this:

    char* CFichierTrace::ConvertBSTRToString(BSTR* str)
    {
       char* buf;

       if ( str == NULL )
       {
          buf = new char[2];
          sprintf_s(buf, 2, "%s", "");
       }
       else
          buf =  _com_util::ConvertBSTRToString(*str);

       return buf;
    }

Upvotes: 2

Related Questions