MoaLaiSkirulais
MoaLaiSkirulais

Reputation: 134

When function return an struct, it keeps at stack or at heap?

Sample:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct Animal{

    char name[100];
    char color[100];

} Animal;

Animal Animal_new() {

    Animal aux;
    return aux;
}

int main() {

    Animal a = Animal_new();    

}

The inner struct is created at stack
The returning is a copy that is moved to the heap?
The returning struct must be free?

Upvotes: 1

Views: 1192

Answers (3)

DMH
DMH

Reputation: 192

The calling function allocated space on its stack for the return struct by the callee.

Basically since, in your example, main knows it's going to receive a struct Animal it automatically creates space on its stack for it and passes a pointer (this is hidden from you but happens at the assembly level) to this newly created stack space to your Animal_New() function.

This function has its own copy of the struct in its stack space, when returning it copies its value to the caller stack space through the pointer it received.

Asked by @MoLaiSkirulais in the comments:

Animal *heapAllocatedAnimal = malloc(sizeof(Animal));
memcpy(heapAllocatedAnimal,&a,sizeof(Animal));

As referenced by @Olaf this a "classical" implementation, which should represent most implementations however knowing is better than assuming so when in doubt read the documentation.

Upvotes: 2

chqrlie
chqrlie

Reputation: 144979

Functions returning a structure can be implemented by the compiler as taking an extra hidden argument, a pointer to the receiving struct in the caller's scope, possibly a temporary one if the result is not stored. The function copies its local copy to the destination one. In your case, both are stored in automatic storage.

If your function had allocated memory from the heap for the structure it returns, the memory would likely become unreachable as the struct is returned by value (copied to the destination) and its address, known to the returning function will eventually be lost.

If the structure is small, the compiler can choose to return it in registers as it does for scalar values.

The ABI defines how these matters are handled. The ABI is system specific, it can be more of less complicated depending on hardware capabilities and implementer's choices.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726919

structs are returned by value. In fact, the only way for anything to get onto the heap is for you to call malloc/calloc/realloc.

The local value of Animal variable is going to be placed in automatic memory. When the value is returned to main, a copy is made from aux of Animal_new to a of main. Compilers, however, can optimize things in a way that prevents copying, but one may not assume that this is true.

Upvotes: 1

Related Questions