M. Timtow M. Timtow - 3 months ago 8
C Question

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))
?

Answer

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.