Is it safe to return a struct in C or C++?

jzepeda picture jzepeda · Mar 6, 2012 · Viewed 65.3k times · Source

What I understand is that this shouldn't be done, but I believe I've seen examples that do something like this (note code is not necessarily syntactically correct but the idea is there)

typedef struct{
    int a,b;
}mystruct;

And then here's a function

mystruct func(int c, int d){
    mystruct retval;
    retval.a = c;
    retval.b = d;
    return retval;
}

I understood that we should always return a pointer to a malloc'ed struct if we want to do something like this, but I'm positive I've seen examples that do something like this. Is this correct? Personally I always either return a pointer to a malloc'ed struct or just do a pass by reference to the function and modify the values there. (Because my understanding is that once the scope of the function is over, whatever stack was used to allocate the structure can be overwritten).

Let's add a second part to the question: Does this vary by compiler? If it does, then what is the behavior for the latest versions of compilers for desktops: gcc, g++ and Visual Studio?

Thoughts on the matter?

Answer

Pablo Santa Cruz picture Pablo Santa Cruz · Mar 6, 2012

It's perfectly safe, and it's not wrong to do so. Also: it does not vary by compiler.

Usually, when (like your example) your struct is not too big I would argue that this approach is even better than returning a malloc'ed structure (malloc is an expensive operation).