Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

Dark GDK / Returning char* from a function

Author
Message
Michael P
18
Years of Service
User Offline
Joined: 6th Mar 2006
Location: London (UK)
Posted: 21st Aug 2008 21:42


Is there a way that I can return char* without having to deallocate the memory once returned?
Benjamin
21
Years of Service
User Offline
Joined: 24th Nov 2002
Location: France
Posted: 21st Aug 2008 21:56
You can use a static pointer:



But note that it won't return a unique buffer each time it is called, as it uses the same memory every time. Alternately, use std::strings or have the function accept a char* as an argument, and write to this instead.

Michael P
18
Years of Service
User Offline
Joined: 6th Mar 2006
Location: London (UK)
Posted: 21st Aug 2008 22:07
On a related topic:

Are we supposed to delete memory for char* from DGDK commands like dbInput or are they returning static pointers?
IanM
Retired Moderator
22
Years of Service
User Offline
Joined: 11th Sep 2002
Location: In my moon base
Posted: 21st Aug 2008 23:27
You need to delete the pointer when you are done. Just use 'delete[] Ptr;' to do the job.

Zotoaster
19
Years of Service
User Offline
Joined: 20th Dec 2004
Location: Scotland
Posted: 22nd Aug 2008 16:42
You could also use the auto_ptr class found in <memory>. It gives you automatic garbage collection IIRC.




I think that's how it works, though I'm not sure.

Don't you just hate that Zotoaster guy?
Lilith
16
Years of Service
User Offline
Joined: 12th Feb 2008
Location: Dallas, TX
Posted: 22nd Aug 2008 17:08
But isn't MyInt out of scope by the time you try to use it in your cout statement?

Lilith, Night Butterfly
I'm not a programmer but I play one in the office
IanM
Retired Moderator
22
Years of Service
User Offline
Joined: 11th Sep 2002
Location: In my moon base
Posted: 22nd Aug 2008 20:55
Apart from Zotoaster's coding problems the other problem with auto_ptr is that it doesn't work correctly with arrays - it will only call the destructor of the first item in the array. That said, it would probably work for a plain type or a POD type, but it's technically undefined behaviour.

If you decide that RAII is the route to go, then the boost shared_array or scoped_array pointer types are the safest I know of.

Zotoaster
19
Years of Service
User Offline
Joined: 20th Dec 2004
Location: Scotland
Posted: 23rd Aug 2008 19:53
Quote: "But isn't MyInt out of scope by the time you try to use it in your cout statement?"


Hmph, you know what I mean Luckily I commented as an error anyway Haha.

Don't you just hate that Zotoaster guy?

Login to post a reply

Server time is: 2024-09-30 05:37:04
Your offset time is: 2024-09-30 05:37:04