[C]When the address returned from the function is referenced later, the value is incorrect
Phenomenon
Create a function (func_a) in C language. Creates an instance of a struct based on the contents of the argument and returns its address.
That address is then used as an argument to another function (func_b). Refers to the address and performs the prescribed processing based on the contents of the struct created by func_a.
typedef struct {
int a;
int b;
}SAMPLE_STRUCT
SAMPLE_STRUCT* func_a(int a, int b){
SAMPLE_STRUCT s;
s.a = a;
s.b = b;
return &s;
}
void func_b(SAMPLE_STRUCT *smpl){
int a =(*smpl).a; //value of a is incorrect
}
When you retrieve the value of member "a" with func_b, it contains a different value from what was set with func_a.
Question: What's wrong with the code above?
Cause
Answer: Because it returns the address allocated as a local variable of the function (func_a).
Local variables of function are allocated on the stack. Even if you refer to that address later, the value stored at that address will be changed because the stack is also used by another function.
Solution
1 return the struct itself
2 Return the address of the variable allocated in the heap with malloc etc.
3 Return the address of the variable allocated as a global variable
SAMPLE_STRUCT* func_a(int a, int b){
SAMPLE_STRUCT *s =
(SAMPLE_STRUCT *)malloc(sizeof(SAMPLE_STRUCT));
s->a = a;
s->b = b;
return s;
}
Lastly
Because I didn't understand memory properly, such a mistake occurred.
Recent Posts
See AllWhat want to do There is an operation that operates on two-dimensional arrays There are multiple targets to be processed In this case, I...
What want to do As stated in the title, I would like to define an array of function pointers. Specifically, for example, the third...
Comments