0

Heres a theoretical question for you assembly experts working in C++. I am often wanting to return a string (char * or wchar *) from a local variable within a function. As you know this cannot be done, as the local variable loses scope. This gets me curious, would it be possible to push the data stored at this location from within the function?

Let me illustrate:

char *IllegalFunc()
{
    char *ret = "Hello World";
    return ret; //warning: returning the adress of a local variable
}

//what we are attempting
char *IllegalAndMostlyIllogicalFunc()
{
    char *ret = "Hello World";
    __asm {
        //somehow copy *ret to ESP and return 
    }
}

char *ARightWayToDoIt()
{
    char *ret = new char[12];    
    strcpy(ret, "Hello World");
    return ret;
}

This is just for curiousity, I wouldn't acctually use __asm method... I will probably just declare a static char * so i can import the function like so in c#

[dllimport(...)]
string IllegalFunc();

[dllimport(...)]
string ARightWayToDoIt(); //memory leak, I would need a FreeLastString() method
4
  • 2
    How can you copy a potentially very long string into the limited space of ESP? Commented Jan 7, 2011 at 20:19
  • By the way, don't be surprised if the CLR yells at you for doing that. Commented Jan 7, 2011 at 20:30
  • IllegalFunc is totally legal. Try it. Commented Jan 8, 2011 at 12:39
  • hrm, ok! in my example its a string literal but thats not ussually the case. thanks for pointing that out! Commented Jan 11, 2011 at 16:08

4 Answers 4

6

That code doesn't leak, as literal strings are statically allocated. It's perfectly legal to return local pointers, but not pointers to locals. However, you could request that the managed user passes the return value to a free function that you write, and then you can malloc- or new.

Sign up to request clarification or add additional context in comments.

Comments

4

Since you're in C++, why not just return std::string?

Edit:

DeadMG points out you're importing the function from C#. The usual approach in C was to pass a character buffer into the function as an argument. From what I've read, that works here too. See, for example, this previous question.

1 Comment

Because he's marshalling it to managed code, which won't take that.
3

As an assembly expert working in C++, I can assure you that in-line assembly code is totally inappropriate here :-)

Comments

1

I'm not an expert, but I do know that prologue and epilogue code can mess up what you want to do. If you're really doing that (which, needless to say, is bad practice), take a look at naked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.