C Heap/Stack and Function Return Value

c

Solution

In your `add()` function, you return the value that is held (until the function exits) in its local variable `result`. The storage for that variable is no longer available once the function returns, but the value that was stored there is just a number, not in itself dependent on that storage.

In your `concat()` function, the expression `result` evaluates to a pointer to the local storage for an array of 10 `char`. You can still return the pointer's value, but once the function exits the meaning of that value is no longer defined.

So, no, the behavior of returning a value does not itself differ between those cases, but the usefulness -- indeed the risk -- associated with doing so varies greatly.

Problem

Apologies if this is a "basic" question, but I am new to C and can't find the answer. My question is regarding the need to `malloc` a variable and return its pointer within a function, compared with creating the variable within the function and `return`ing the result. The first issue that comes to mind is that any variables declared within the scope of the function will be destroyed once the function terminates; so why is it then that the following is valid: ``` int add(int a, int b) { int result; result = a + b; return result; } ``` But the following is not? ``` char *concat(char* a, char* b) { char result[10]; strcat(result, a); strcat(result, b); return result; } ``` The warning you get is that you are returning an address to a local variable, but this is what we are also doing in the first function? Does the behaviour differ depending on the type? For a more real example, I'm very confused regarding which of the following 2 functions I should be using, as they both work perfectly well for my program: ``` struct Card *card_create(enum Rank rank, enum Suit suit) { struct Card *card = malloc(sizeof(struct Card)); if(card == NULL) { fprintf(stderr, "malloc: %s", strerror(errno)); return NULL; } card->rank = rank; card->suit = suit; return card; } ``` Or: ``` struct Card card_create(enum Rank rank, enum Suit suit) { struct Card card; card.rank = rank; card.suit = suit; return card; } ``` Again, sorry if this is a nooby question, but I'd really appreciate an explanation. Thanks!

Original source

Related problems