Skip to main content
GameDev.net gamedev.net
🔒 Locked

char pointers

Started by CD579 Dec 30, 2003 at 5:59 PM 3 replies 800+ views
Original Post
CD579
CD579
Okay guys, I've racked my brains, looked in my c++ books, and searched google, but I couldn't find a solution to my problem. I want to return a character array without having to delete the return value. Here is a simplified version of my function that doesn't work. The buffer array is on the stack and goes out of scope when my function returns so all I get is a bunch of garbage. Yes, len is defined and has a value, but it's not important.
//Doesn't work:
char* GetText(){
    char buffer[len+1];
    return buffer;
}

//But I don't want to do this:
char* GetText(){
    char* buffer;
    buffer = new char[len+1];
    return buffer;
}

//because I would have to do this everytime I use said function:
char* ret = GetText();
// use return value
delete ret;
  
If I don't delete the pointer I get a memory leak. Any ideas? I don't want to use std::string, because I feel as though I don't need to use if for something so simple. Thanks a bunch guys! CD Jesus is Lord!! [edited by - CD579 on December 30, 2003 7:00:27 PM]
Jesus is Lord!!
Fruny
Fruny
The possible solutions depend on what you need that buffer for.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
antareus
antareus
quote:
I want to return a character array without having to delete the return value.

Those requirements point to std::string. Use it, love it.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
brassfish89
brassfish89
You could use a static buffer and return a pointer to that, ofcourse the downside is that its size is static and it''ll increase your executable size. If you are working in C++ then std::string is probably the best choice.

--------
"Hey, what about those baggy pants you kids are wearin'' these days? Aren''t they hip and cool and poppin'' fresh?"-Peter Griffin
"Everytime I see an M followed by a dollar sign I just say "oh god" and go to the next post."-Neurokaotix
the D programming language|google|msdn|XLib reference manual
CD579
CD579
Okay, I guess I''ll just use std::string then. Thanks for the replys guys.

CD

Jesus is Lord!!
Jesus is Lord!!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.