top of page

[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 All

[C] Array of function pointers

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


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page