Q:

Is it safe for a subroutine to write in the stack of its calling routine?

I am currently using a routine String_concat(char *str1, char *str2) which, as its name suggest, concatenates two strings. To do so, this routine dynamically allocates memory on the heap (via malloc()). However, since the returned string is only used in the calling routine, I am thinking of directly allocating memory on the stack (via alloca()), hence I would replace String_concat() with something like String_concat2(char* str1, char* str2, char* dest) which would take the destination buffer (already allocated on the stack) as an argument. So my question is : Is is ok for String_concat2() to write in the stack of its calling routine, or must I force inlining via __attribute__((always_inline)) ?

A:

There is no problem for a function to write in the stack frame of its calling function.
For example:
void foo(int *ptr) {
    *ptr = 7;
}

void bar(void) {
    int value;
    foo(&value);
}

In the above code, foo function is writing to a location which is in the stack frame of the bar function that calls it.

A:

A callee routine can always modify values in its caller. But unless you want to use assembly language to mimic what compiler does it cannot allocate space in caller stack because its own variables are already there.
When you need to return an array to your caller, the only two portable ways are:

callee allocates memory with malloc and pass that address to its caller - the caller will later free the memory block
caller pre-allocates memory and pass a buffer to the callee - the callee only fills the buffer and does not worry where it is allocated not whether it is allocated at all (might be static or automatic storage)

