0

background

typedef struct Result {
  int type;
  union {
    Err err;
    Table tbl;
   };
} Result;

typedef struct Err {
  int status;
  String command;
  String err;
} Err;


Result *getres(...) {
  ....

  return &(Result) {....};
}

void somefun(..) {
  ...
  Result *res = getres(..);
  // (A)
  handleres(res);
}

void handleres(Result *res) {
  // (B)
  ...
}

(A) at point A, res has the expected data passed from getres, but point (B) has different data, and debugging the code view that most of res elements pointers has the same pointer of res!!, not just the first element, except one element res->err->err;

in assembly sense

getres return pointer to local Result in eax, which mapps to span -start(ebp) to -end(ebp) of getres routine.

question

dynamic allocation works, but why statically defined struct pointer behave that way, does assembly frames gets used and -start(ebp), -end(ebp) get overwritten?

Frank C.
  • 7,758
  • 4
  • 35
  • 45
Error
  • 820
  • 1
  • 11
  • 34
  • an assembly question without any assembly? – old_timer May 13 '17 at 19:28
  • Yes, stack get reused. You shouldn't return a pointer to a local variable (if that's what you are doing) as those will go out of scope at end of function and the memory may be reused. – Jester May 13 '17 at 19:28
  • @Jester then when statically defined struct pointer is useful? – Error May 13 '17 at 19:30
  • @Jester that answers, you can write in details answer for first question to close the question? and any insight about the second in comment – Error May 13 '17 at 19:32
  • 3
    Possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Raymond Chen May 13 '17 at 19:46
  • @Jester now i understand static struct is safe to use just upon return only. – Error May 13 '17 at 20:02

0 Answers0