473,581 Members | 2,338 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to return a string of arbitrary length to caller?

Hi,

I'm writing a library in C++ which is supposed to be used by people using C.
One function I have must return a string to users which is arbitrary length.
The user must be able to use this string as "char *" so I was wondering if
the following construct is safe:

char *Func()
{
static string str;

str = "foobar..." ;

return (char *) str.c_str();
}

The problem is that before the function call the length of the string is
unknown.
An alternative is to use malloc or new and provide that pointer to the user.
The memory allocated could then be deallocated later on.

Thanks in advance.
-- John
Jul 22 '05 #1
8 2347

"John Smith" <jo********@int heunknown.net> wrote in message
news:40******** *************@d read11.news.tel e.dk...
Hi,

I'm writing a library in C++ which is supposed to be used by people using C. One function I have must return a string to users which is arbitrary length. The user must be able to use this string as "char *" so I was wondering if
the following construct is safe:

char *Func()
{
static string str;

str = "foobar..." ;

return (char *) str.c_str();
}
No its not safe, for two reasons. Firstly you are casting away const, if you
users ever use the non-const pointer to change the value of the string then
you are invoking undefined behaviour. Secondly the use of a static variable
might be problematic, what if Func is called twice? If the user still has
the pointer that was the result of the first call to Func then the second
call would change what that pointer is pointing to (I'm assuming that each
call to Func produces a different string).

The problem is that before the function call the length of the string is
unknown.
An alternative is to use malloc or new and provide that pointer to the user. The memory allocated could then be deallocated later on.

That's the way to do it. Since you are dealing with C, presumably malloc
would be a better bet.
Thanks in advance.
-- John

Jul 22 '05 #2
On Thu, 22 Apr 2004, John Harrison wrote:

"John Smith" <jo********@int heunknown.net> wrote in message
news:40******* **************@ dread11.news.te le.dk...
Hi,

I'm writing a library in C++ which is supposed to be used by people using

C.
One function I have must return a string to users which is arbitrary

length.
The user must be able to use this string as "char *" so I was wondering if
the following construct is safe:

char *Func()
{
static string str;

str = "foobar..." ;

return (char *) str.c_str();
}


No its not safe, for two reasons. Firstly you are casting away const, if you
users ever use the non-const pointer to change the value of the string then
you are invoking undefined behaviour. Secondly the use of a static variable
might be problematic, what if Func is called twice? If the user still has
the pointer that was the result of the first call to Func then the second
call would change what that pointer is pointing to (I'm assuming that each
call to Func produces a different string).

The problem is that before the function call the length of the string is
unknown.
An alternative is to use malloc or new and provide that pointer to the

user.
The memory allocated could then be deallocated later on.


That's the way to do it. Since you are dealing with C, presumably malloc
would be a better bet.


Definitely, don't use new or new[] if the string can only be deallocated
with free().

Another way would be to let the caller pass you an allocated char* and
its size. The advantage of this being that the string can be allocated
and deallocated in the same context. Obviously this requires that the
caller knows which size is required, so it may not be applicable.

--
Claudio Jolowicz
http://www.doc.ic.ac.uk/~cj603

Jul 22 '05 #3
On Thu, 22 Apr 2004, Claudio Jolowicz wrote:
An alternative is to use malloc or new and provide that pointer to theuser.
The memory allocated could then be deallocated later on.


That's the way to do it. Since you are dealing with C, presumably malloc
would be a better bet.


Definitely, don't use new or new[] if the string can only be deallocated
with free().


Actually, you /could/ use new and provide a function to deallocate the
string in the proper way.
Another way would be to let the caller pass you an allocated char* and
its size. The advantage of this being that the string can be allocated
and deallocated in the same context. Obviously this requires that the
caller knows which size is required, so it may not be applicable.


--
Claudio Jolowicz
http://www.doc.ic.ac.uk/~cj603

Jul 22 '05 #4
> An alternative is to use malloc or new and provide that pointer to the user.
The memory allocated could then be deallocated later on.


As John Harrison already said, of both your ideas this is the way to go.
Your system might have the convenience function "strdup()", so you
merge "std::string::s ize()", "malloc()" and "strcpy()" into one call. But then,
be aware, that "strdup()" might internally use "new []" instead of "malloc()".
Sun CC 5.3 seems to do this as Purify told me, which I consider a bad
decision...

I'd go for a third way, however: Adopt the way, the Unix "*_r()" routines
work: Pass a pointer to a user supplied buffer and the length of this buffer by
argument. For convenience, you could return the pointer to the buffer
again to the caller. This style has three advantages: It's known to callers from
e.g. the "*_r()" routines, it's less prone to memory leaks - functions
returning pointers to memory they've just allocated suffer from
potentially being wrongly used -, and the caller can decide himself which
memory allocation he uses - local variables, "malloc()", "mmap()"... Of
course, there's also a disadvantage: What to do, if the buffer is too small?
One of the easier ways out of this disadvantage is another function, which
calculates the size of the buffer in advance and return it to the caller. Take a
look e.g. at MS Win32 "GetSystemDirec tory()", which can act both as a
function which returns the length of the buffer required and as a function
which actually fills the buffer.

Cheers,
Philipp.


Jul 22 '05 #5
John Smith wrote:

Hi,

I'm writing a library in C++ which is supposed to be used by people using C.
One function I have must return a string to users which is arbitrary length.
The user must be able to use this string as "char *" so I was wondering if
the following construct is safe:

char *Func()
{
static string str;

str = "foobar..." ;

return (char *) str.c_str();
}

The problem is that before the function call the length of the string is
unknown.
An alternative is to use malloc or new and provide that pointer to the user.
The memory allocated could then be deallocated later on.

Thanks in advance.
-- John


Using your method is acceptable provided your callers can live w/ the side
effects of using a shared storage location.

One way would be to return the required length of the string and let the user
allocate the required space. The negative effect is that essentially the
function has to be called twice:

int Func(char * dest, int cchdest)
{
// get string as 'std::string', store required length
// if dest is NULL, don't store result
return requiredlength;
}

Another method is to have the caller pass in a function address that is used by
you to allocate the required space, and then leave it up to the caller to free
the memory:

typedef void * (Allocator)(int size);
char * Func(Allocator alloc)
{
char * dest = (char *)alloc(require dsize);
// ...
return dest;
}

A note, if you define the Allocator signature the same as malloc, that would
allow your users to use it directly, minimizing the fuss:

// caller's code:
char * newstring = Func(malloc);
// use newstring
free(newstring) ; // all done!
Jul 22 '05 #6
"Claudio Jolowicz" <cj***@doc.ic.a c.uk> wrote in message
news:Pi******** *************** ********@thrush .doc.ic.ac.uk.. .
Another way would be to let the caller pass you an allocated char* and
its size. The advantage of this being that the string can be allocated
and deallocated in the same context. Obviously this requires that the
caller knows which size is required, so it may not be applicable.


Solution might be to have the function always return the number of
chars written to the buffer, and if the buffer size is 0, return the number
of chars needed.

hth
--
jb

(replace y with x if you want to reply by e-mail)
Jul 22 '05 #7
"John Smith" <jo********@int heunknown.net> wrote in message news:<40******* **************@ dread11.news.te le.dk>...
Hi,

I'm writing a library in C++ which is supposed to be used by people using C.
One function I have must return a string to users which is arbitrary length.
The user must be able to use this string as "char *" so I was wondering if
the following construct is safe:

char *Func()
{
static string str;

str = "foobar..." ;

return (char *) str.c_str();
}

The problem is that before the function call the length of the string is
unknown.
An alternative is to use malloc or new and provide that pointer to the user.
The memory allocated could then be deallocated later on.

Thanks in advance.
-- John


Well .. I think passing a char * allocated from inside the C++ to an
external C routine is fundamentally unsafe .. it would be much better
to pass in an allocated char * and an int describing the length as
suggested by another user. However I understand you might not have
much choice if you are dealing with legacy code. Lets assume you can
guarantee that the C code will not try to access beyond the end of the
string .. otherwise you are sunk. Lets also assume that the C-code
will not try to de-allocate the memory for the char *.

If both of the above are true, I think a factory approach like the
following might be useful:

#include <vector>
#include <string>

using std::string;
using std::vector;

class string_maker : vector<char *> {
public:
char * new_string(stri ng s) { // you could also use const char
char *p = new char[s.length()+1];
s.copy(p,string ::npos);
p[s.length()] = 0; // add C-style string terminator
push_back(p);
return p;
}

~string_maker() {
// free memory
vector<char *>::iterator I=begin();
for ( ; I!=end(); ++I)
delete [] *I;
}
};

// put this in the same translation unit as Func below.
namespace {
string_maker repository;
}

// now for your function

int Func(char *&p) {
string return_string;
// dynamic generation of return_string contents
p=repository.ne w_string(return _string);
return return_string.l ength()+1;
}

Notice I have changed the declaration of Func so that it returns the
length of the string as an int, which is essential so that the C-code
calling the function can make sure not to overrun the result. The
(unallocated) char * addressing the result is passed *by reference* to
Func as an argument. (Leaving out the reference means only the local
copy is modified).

Now, while I would really not advise doing things this way, I guess
this might work for you, given the caveats above. At least the
allocation and deallocation of memory is handled in a well defined
way, and you can be fairly sure that the char *'s being passed between
C and C++ will not be invalidated before the program exit.

Of course, many improvements could be made to the string_maker class
above .. it is just a (hopefully) helpful idea.

HTH, Dave Moore
Jul 22 '05 #8
Thank you all for the useful suggestions and comments.

I discovered the best thing for me would be to do something like the
following.
Since I provide a complete api with C-frontend I can just do whatever I want
inside e.g.:

class MemoryHolder
{
public:
char *p;
};
char *Func(void *pHandle)
{
string str = ... my data;
MemoryHolder M = pHandle; // <- void pointer is really a memory object
M.p = new[..];
strcpy(M.p, str.c_str());
return M.p;
}

void Cleanup(void *pHandle)
{
... cleanup used memory
}

This example is naturally incomplete but thats just to show what I'm
thinking.
The user which only uses C has a void pointer handle which is a object
pointer. Inside I can cast the void pointer to my real type and hide the
real implementation (e.g. you don't need to put the classes in public
available header files).
To those who asked about legacy code I don't have any legacy. All is
developed from scratch but it's a requirement that my code can be used from
various languages including C.
The idea that some people recommended about passing NULL and then returning
length is sort of ok but the computation time for the function might be a
while so its useless to do the same calculations twice.

-- John
Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

66
4947
by: Darren Dale | last post by:
Hello, def test(data): i = ? This is the line I have trouble with if i==1: return data else: return data a,b,c,d = test()
3
1593
by: Zork | last post by:
Hi, I am a little confused with const functions, for instance (here i am just overloading the unary+ operator) if i define: 1) Length Length :: operator+ ( void ) const {return * this;} ... I get no error... 2) Length & Length :: operator+ ( void ) const {return * this;} ... I get the error -> 'return' : cannot convert from 'const...
7
38827
by: Fernando | last post by:
Hello, I want call, from main program, to a function (with void arguments), what it run the function program and return the data of type char. I have make a example of code, by it don´t run, I can´t compile. I beleave what I have problems with the concept of the arrays and the pointers: #include <stdio.h> char composefile(void); main () {...
4
1547
by: Kelvin | last post by:
hi: if i want a function to return me a string, how can I do it? i know one method is by passing a string pointer to a function. is there any implementation? thank you very much -- { Kelvin@!!! }
23
3569
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
0
992
by: Fritz | last post by:
Hi, My problem is getting a string of variable length from a unmanaged DLL, called by a managed DLL using IJW. In der legacy DLL is declared bool UnmanagerClass::GetData(std::wstring* pString) { // content of pString as input by the caller is received correct *pString = L"the string to return";
16
4889
by: Dany | last post by:
Our web service was working fine until we installed .net Framework 1.1 service pack 1. Uninstalling SP1 is not an option because our largest customer says service packs marked as "critical" by Microsoft must be installed on their servers. Now german Umlaute (ä, ü, ö) and quotes are returned incorrectly in SOAP fault responses. This can be...
10
5892
by: vignesh4u | last post by:
I am trying to implement the Split function in C ie. if i have a string: char* S="This is a test"; and if i try to split based on space ' ' it should return an array of strings like: {"This","is","a","test"} . I tried to implement it as given below but am getting a segmentation fault. I would really appreciate if some one could give me...
6
1974
by: MN | last post by:
I have 2 questions: 1- Why isn't possible to declare a static char array inside function ? the compiler gives this error: storage size of ‘array’ isn’t constant. 2- Why isn't possible to output the whole array with 2 dimensions from function? my function looks like this:
0
7862
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7789
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7894
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8169
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6551
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5670
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3820
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1400
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1132
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.