M. Timtow M. Timtow - 1 year ago 57
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
). However, since the returned string is only used in the calling routine, I am thinking of directly allocating memory on the stack (via
), hence I would replace
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
to write in the stack of its calling routine, or must I force inlining via

Answer Source

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;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download