Re: [cc65] returning structs

From: Marc 'BlackJack' Rintsch <>
Date: 2009-08-10 12:36:05
Groepaz wrote:
> On Montag 10 August 2009, Oliver Schmidt wrote:
>> Hi Groepaz,
>>>> I know that you cant return a struct by value.  Is there any way around
>>>> this?  If I return a pointer to the struct, the values are lost upon
>>>> leaving the function.  Can anyone provide an example workaround?
>>> make it return a pointer, and then copy it to a local struct:
>>> memcpy(&localstruct,functhatreturnsstruct(),sizeof(localstruct));
>>> (thats pretty much almost exactly what a compiler would do too)
>> Maybe it's woth mentioning that your proposal presumes that memcpy()
>> a) is inlined / is a specially designed intrinsic / <you name it>
>> b) doesn't use the stack itself
>> because otherwise calling it could overwrite the data you want to
>> copy. From that perspective I'd rather classify this approach as hack
>> than as workaround.
> hu? how would calling memcpy destroy the data that was passed to it?

It does not destroy the data passed to it, but may destroy the data the
pointer returned by `functhatreturnsstruct()` points to.  Example:

typedef struct {
    char x, y;
} bar;

*bar foo() {
    bar result;
    result.x = 42;
    result.y = 23;
    return &result;

int main(void) {
    bar local;
    memcpy(&local, foo(), sizeof(local));
    return 0;

`foo()` is called and returns a pointer to `result` on the stack and
before `memcpy()` is called this area is destroyed by overwriting it
with `memcpy()`\s arguments.

	Marc 'BlackJack' Rintsch

To unsubscribe from the list send mail to with
the string "unsubscribe cc65" in the body(!) of the mail.
Received on Mon Aug 10 12:36:21 2009

This archive was generated by hypermail 2.1.8 : 2009-08-10 12:36:23 CEST