Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

returning a BSTR in Visual C++

0 views
Skip to first unread message

Bill Jones

unread,
Jun 17, 1997, 3:00:00 AM6/17/97
to

Using the class wizard in Visual C++ 4.1, the following code is created for
a function that returns a string:

BSTR CMyClassDoc::GetName()
{
CString strResult;

strResult = "Some Name"; // Not created by wizard

return strResult.AllocSysString();
}

according to the comp.lang.c FAQ, similar code is strictly advised against:

char *GetName()
{
char name[20]; /* WRONG */

strcpy(name,"Some Name");

return name; /* WRONG */
}

The reason is because as soon as the function exits, the memory holding the
"name" string is no longer guaranteed, and could be overwritten. Is the
above C++ example safe to use? (We have been using the C++ code in an OLE
automation server for some time with no apparent ill effects).


--
--
Bill Jones e-mail addresses:
Computer Sciences Corp. (work) wjon...@csc.com
Norwich, Connecticut (play) bi...@mindport.net
(860) 437-5650 WWW: http://www.mindport.net/~billj


Ennals

unread,
Jun 18, 1997, 3:00:00 AM6/18/97
to

In article <01bc7b31$039d84c0$e7f2...@plunger.gdeb.com>, "Bill Jones"
<wjon...@csc.com> writes:

>
>BSTR CMyClassDoc::GetName()
>{
> CString strResult;
>
> strResult = "Some Name"; // Not created by wizard
>
> return strResult.AllocSysString();
>}

This is safe as AllocSysString allocates new memory for the object. The
data passed back is on the heap rather than the stack.

>according to the comp.lang.c FAQ, similar code is strictly advised
against:
>
>char *GetName()
>{
> char name[20]; /* WRONG */
>
> strcpy(name,"Some Name");
>
> return name; /* WRONG */
>}

This is unsafe as name points to an array allocated on the stack, which
will be deallocated.

********************************************************************
Robert Ennals / email: enn...@aol.com
url: http://members.aol.com/ennals/index.html
"If at first you don't succeed, redefine 'succeed' "
Mathematics - The joy of sec

0 new messages