JJJ
JJJ

Reputation: 135

Can a returned struct be overwritten?

I have a struct that is returned by some function:

struct Abc {
    char *a;
    int b;
};

static struct Abc foo() {
    struct Abc mystruct;
    mystruct.a = "asdf";
    mystruct.b = 1;

    return mystruct;
}

If I call struct Abc new_abc = foo();, is it possible for the struct stored in new_abc to be overwritten by the program?

If I understand correctly, mystruct is an automatic variable which is local in scope. Thus the reference might be left dangling and hence can be overwritten.

Upvotes: 3

Views: 94

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134376

If I call struct Abc new_abc = foo();, is it possible for the struct stored in new_abc to be overwritten by the program?

Yes, new_abc is just another variable. It can be overwritten is the program(mer) wishes so.

If I understand correctly, mystruct is an automatic variable which is local in scope. Thus the reference might be left dangling and hence can be overwritten.

You are not returning the address of the local variable, you're returning the value. Returning a structure variable is functionally same as returning a local int or char. There's no dangling pointer here.


EDIT:

As clarified in the comments:

"will it ever be overwritten by the program allocating memory for other things"

The answer is no. You're returning the value and storing it in a variable. Sure, if you create too many local variables, you may face stack overflow, but the allocated memory for a automatic local variable (which is used to store the returned value) will not be claimed back unless it goes out of scope.

In other words, once the value of the local variable is returned from the function and stored in another variable in the caller, the local variable in the function need no exist anymore to be able access the stored value in the caller.

Upvotes: 4

Related Questions