Modify the contents of the memory address of the return of a function

  • A+
Category:Languages

Is it possible to modify the contents of the memory address of the return value of a function? functions return the value of a locally defined variable.

In the following example, compiled for my machine (x86-64) without warnings:

#include <stdio.h>  int get_val1() {   int ret = 1;   return ret; }  int get_val2() {   int ret = 2;   return ret; }  int get_val3() {   int ret = 3;   return ret; }  void redefine_ints(int *val1, int *val2, int *val3) {   *val1 = 10;   *val2 = 11;   *val3 = 12; }  void print_and_redefine_ints(int val1, int val2, int val3) {   printf("val1 %d val2 %d val3 %d/n", val1, val2, val3);   redefine_ints(&val1, &val2, &val3);   printf("rval1 %d rval2 %d rval3 %d/n", val1, val2, val3); }  int main() {   print_and_redefine_ints(get_val1(), get_val2(), get_val3());   return 0; } 

I get the next output:

val1 1 val2 2 val3 3 rval1 10 rval2 11 rval3 12 

This is the expected output, but how is it possible? Where are these variables stored?

 


Yes this is well-defined C.

The anonymous temporary ints created by get_val...() have a lifetime contemporaneous with the entire statement in which they are created.

But note that you take a value copy of each of these ints when you call print_and_redefine_ints so there's nothing particularly special going on here.

(Note that you would not be able to bind pointers to the anonymous temporary ints to int* function parameters though.)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: